前端代码:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>导入Excel表格</title>
</head>
<!-- uncomment the next line here and in xlsxworker.js for encoding support -->
<script src="dist/cpexcel.js"></script>
<script src="shim.js"></script>
<script src="jszip.js"></script>
<script src="xlsx.js"></script>
<script src="xlsxworker.js"></script>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
function AllSelectCheck(){
var checkAll=$("input[name='checkbox']");
var checkbox=$("input[id='allCheckBox']");
//alert(checkbox);
if ( checkAll[0].checked == true){
checkAll.prop("checked", true);
//checkAll.attr("checked",true);
//alert("good day");
}else{
// alert("good day2");
//checkAll.attr("checked",false);
checkAll.prop("checked", false);
}
}
function Importdata(){
var trnum=$("tr");
var tables=$("table");
var datatable=[];
//alert($("table").find("td").eq(1).text());
alert($("table").find("tr").eq(1).find("td").eq(1).text());
var datajson=new Array();
var jsonlist=new Array();
var index=0;
for(var i=1;i<trnum.length;i++){
var obj={};
obj["sId"]=$("table").find("tr").eq(i).find("td").eq(0).text();
obj["sNo"]=$("table").find("tr").eq(i).find("td").eq(1).text();
obj["sName"]=$("table").find("tr").eq(i).find("td").eq(2).text();
obj["sWno"]=$("table").find("tr").eq(i).find("td").eq(3).text();
obj["sUid"]=$("table").find("tr").eq(i).find("td").eq(4).text();
jsonlist[index]=obj;
index++;
//datajson[i]=new Array();
//for(var col=0;col<$("tr").eq(1).find("td").length;col++){
// var namevalue=$("table").find("tr").eq(i).find("td").eq(col).text();
// datajson[i][col]=namevalue;
//}
//datatable.push({
// sId:$("table").find("tr").eq(i).find("td").eq(0).text(),
// sNo:$("table").find("tr").eq(i).find("td").eq(1).text(),
// sName:$("table").find("tr").eq(i).find("td").eq(2).text(),
// sWno:$("table").find("tr").eq(i).find("td").eq(3).text()
// });
}
var json = JSON.stringify(jsonlist);
alert("json数组为:"+json);
//ocation="../ImportExcel.action?json="+json;
$.ajax({
url:"../ImportExcel.action",
type:"post",
//dataType:"json",
data:{
"json":json
},
success:function(data){
alert("data:"+data);
},
error:function(error){
alert("error:"+error);
}
});
alert("success");
}
</script>
<style>
#drop{
border:0px dashed #bbb;
-moz-border-radius:0px;
-webkit-border-radius:0px;
border-radius:0px;
padding:20px;
text-align:center;
font:20pt bold,"Vollkorn";color:#bbb
}
#b64data{
width:100%;
}
a { text-decoration: none }
tr{
background-color: burlywood;
color: white;
font: 20px bold,"Vollkorn";
}
</style>
<body>
<div><button onclick="Importdata()">导入数据</button></div>
<pre>
<input type="file" name="xlfile" id="xlf" />
<pre id="out"></pre>
<div id="htmlout"></div>
<select name="format" onchange="setfmt()" style="display: none;">
<option value="csv" > CSV</option>
<option value="json"> JSON</option>
<option value="form"> FORMULAE</option>
<option value="html" selected> HTML</option>
</select><br />
<div id="drop"></div>
<input style="display: none;" type="button" id="dotext" value="Click here to process the base64 text" onclick="b64it();"/><br />
<input style="display: none;" type="checkbox" name="useworker" checked>
<input style="display: none;" type="checkbox" name="userabs" checked>
</pre>
<br />
<script>
/*jshint browser:true */
/* eslint-env browser */
/*global Uint8Array, console */
/*global XLSX */
/* exported b64it, setfmt */
/* eslint no-use-before-define:0 */
var X = XLSX;
var XW = {
/* worker message */
msg: 'xlsx',
/* worker scripts */
worker: './xlsxworker.js'
};
var global_wb;
var process_wb = (function() {
var OUT = document.getElementById('out');
var HTMLOUT = document.getElementById('htmlout');
var get_format = (function() {
var radios = document.getElementsByName( "format" );
return function() {
for(var i = 0; i < radios.length; ++i) if(radios[i].checked || radios.length === 1) return radios[i].value;
};
})();
var to_json = function to_json(workbook) {
var result = {};
workbook.SheetNames.forEach(function(sheetName) {
var roa = X.utils.sheet_to_json(workbook.Sheets[sheetName], {header:1});
if(roa.length) result[sheetName] = roa;
});
return JSON.stringify(result, 2, 2);
};
var to_csv = function to_csv(workbook) {
var result = [];
workbook.SheetNames.forEach(function(sheetName) {
var csv = X.utils.sheet_to_csv(workbook.Sheets[sheetName]);
if(csv.length){
result.push("SHEET: " + sheetName);
result.push("");
result.push(csv);
}
});
return result.join("\n");
};
var to_fmla = function to_fmla(workbook) {
var result = [];
workbook.SheetNames.forEach(function(sheetName) {
var formulae = X.utils.get_formulae(workbook.Sheets[sheetName]);
if(formulae.length){
result.push("SHEET: " + sheetName);
result.push("");
result.push(formulae.join("\n"));
}
});
return result.join("\n");
};
var to_html = function to_html(workbook) {
HTMLOUT.innerHTML = "";
workbook.SheetNames.forEach(function(sheetName) {
var htmlstr = X.write(workbook, {sheet:sheetName, type:'string', bookType:'html'});
HTMLOUT.innerHTML += htmlstr;
//alert(HTMLOUT.innerHTML);
var trList = $("tbody").children("tr");
//alert("测试:"+trList.length);
for (var i=0;i<trList.length;i++) {
if(i==0){
$("#sjs-A1").before("<td><input type='checkbox' id='allCheckBox' onclick='AllSelectCheck()' style='width:20px;height:20px;' name='checkbox' value=''/>全选</td>");
}else if(i>0){
var num=i+1;
var tableid="#sjs-A"+num;
$(tableid).before("<td><input type='checkbox' id='items' style='width:20px;height:20px;' name='checkbox'/>"+i+"</td>");
}
}
});
return "";
};
return function process_wb(wb) {
global_wb = wb;
var output = "";
switch(get_format()) {
case "form": output = to_fmla(wb); break;
case "html": output = to_html(wb); break;
case "json": output = to_json(wb); break;
default: output = to_csv(wb);
}
if(OUT.innerText === undefined) OUT.textContent = output;
else OUT.innerText = output;
if(typeof console !== 'undefined') console.log("output", new Date());
};
})();
var setfmt = window.setfmt = function setfmt() { if(global_wb) process_wb(global_wb); };
var b64it = window.b64it = (function() {
var tarea = document.getElementById('b64data');
return function b64it() {
if(typeof console !== 'undefined') console.log("onload", new Date());
var wb = X.read(tarea.value, {type:'base64', WTF:false});
process_wb(wb);
};
})();
var do_file = (function() {
var rABS = typeof FileReader !== "undefined" && (FileReader.prototype||{}).readAsBinaryString;
var domrabs = document.getElementsByName("userabs")[0];
if(!rABS) domrabs.disabled = !(domrabs.checked = false);
var use_worker = typeof Worker !== 'undefined';
var domwork = document.getElementsByName("useworker")[0];
if(!use_worker) domwork.disabled = !(domwork.checked = false);
var xw = function xw(data, cb) {
var worker = new Worker(XW.worker);
worker.onmessage = function(e) {
switch(e.data.t) {
case 'ready': break;
case 'e': console.error(e.data.d); break;
case XW.msg: cb(JSON.parse(e.data.d)); break;
}
};
worker.postMessage({d:data,b:rABS?'binary':'array'});
};
return function do_file(files) {
rABS = domrabs.checked;
use_worker = domwork.checked;
var f = files[0];
var reader = new FileReader();
reader.onload = function(e) {
if(typeof console !== 'undefined') console.log("onload", new Date(), rABS, use_worker);
var data = e.target.result;
if(!rABS) data = new Uint8Array(data);
if(use_worker) xw(data, process_wb);
else process_wb(X.read(data, {type: rABS ? 'binary' : 'array'}));
};
if(rABS) reader.readAsBinaryString(f);
else reader.readAsArrayBuffer(f);
};
})();
(function() {
var drop = document.getElementById('drop');
if(!drop.addEventListener) return;
function handleDrop(e) {
e.stopPropagation();
e.preventDefault();
do_file(e.dataTransfer.files);
}
function handleDragover(e) {
e.stopPropagation();
e.preventDefault();
e.dataTransfer.dropEffect = 'copy';
}
drop.addEventListener('dragenter', handleDragover, false);
drop.addEventListener('dragover', handleDragover, false);
drop.addEventListener('drop', handleDrop, false);
})();
(function() {
var xlf = document.getElementById('xlf');
if(!xlf.addEventListener) return;
function handleFile(e) { do_file(e.target.files); }
xlf.addEventListener('change', handleFile, false);
})();
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-36810333-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</body>
</html>
后台代码:
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import cn.hyqdxt.pojo.Staff;
import cn.hyqdxt.service.CompanyService;
@Controller
public class ImportExcelData {
@Resource
private CompanyService companyService;
@ResponseBody
@RequestMapping("/ImportExcel")
public Map<String,Object> ImportExcel(Model model,HttpSession session, @RequestParam(value="json",required=false)String json)
{
List<Staff> users = JSON.parseArray(json, Staff.class);
for (Staff staff : users) {
System.out.println("序号:"+staff.getsId()+"姓名:"+staff.getsName()+"卡号:"+staff.getsUid()+"会员编号:"+staff.getsWno());
}
String success="成功!";
Map<String, Object> map=new HashMap<String, Object>();
map.put("success", success);
return map;
}
}
注意:后台代码的返回值不能是:String类型,否则Ajax请求会返回error方法