网页表格导入导出Excel
用JS实现网页表格数据导入导出excel。
首先是JS文件中的代码
(function($){
function getRows(target){
var state = $(target).data('datagrid');
if (state.filterSource){
return state.filterSource.rows;
} else {
return state.data.rows;
}
}
function toHtml(target, rows){
rows = rows || getRows(target);
var dg = $(target);
var data = ['<table border="1" rull="all" style="border-collapse:collapse">'];
var fields = dg.datagrid('getColumnFields',true).concat(dg.datagrid('getColumnFields',false));
var trStyle = 'height:32px';
var tdStyle0 = 'vertical-align:middle;padding:0 4px';
data.push('<tr style="'+trStyle+'">');
for(var i=0; i<fields.length-1; i++){
var col = dg.datagrid('getColumnOption', fields[i]);
var tdStyle = tdStyle0 + ';width:'+col.boxWidth+'px;';
data.push('<th style="'+tdStyle+'">'+col.title+'</th>');
}
data.push('</tr>');
$.map(rows, function(row){
data.push('<tr style="'+trStyle+'">');
for(var i=0; i<fields.length-1; i++){
var field = fields[i];
if (row[field] == null){
row[field] = "";
}
data.push(
'<td style="'+tdStyle0+'">'+row[field]+'</td>'
);
}
data.push('</tr>');
});
data.push('</table>');
return data.join('');
}
function toArray(target, rows){
rows = rows || getRows(target);
var dg = $(target);
var fields = dg.datagrid('getColumnFields',true).concat(dg.datagrid('getColumnFields',false));
var data = [];
var r = [];
for(var i=0; i<fields.length; i++){
var col = dg.datagrid('getColumnOption', fields[i]);
r.push(col.title);
}
data.push(r);
$.map(rows, function(row){
var r = [];
for(var i=0; i<fields.length; i++){
r.push(row[fields[i]]);
}
data.push(r);
});
return data;
}
function print(target, param){
var title = null;
var rows = null;
if (typeof param == 'string'){
title = param;
} else {
title = param['title'];
rows = param['rows'];
}
var newWindow = window.open('', '', 'width=800, height=500');
var document = newWindow.document.open();
var content =
'<!doctype html>' +
'<html>' +
'<head>' +
'<meta charset="utf-8">' +
'<title>'+title+'</title>' +
'</head>' +
'<body>' + toHtml(target, rows) + '</body>' +
'</html>';
document.write(content);
document.close();
newWindow.print();
}
function b64toBlob(data){
var sliceSize = 512;
var chars = atob(data);
var byteArrays = [];
for(var offset=0; offset<chars.length; offset+=sliceSize){
var slice = chars.slice(offset, offset+sliceSize);
var byteNumbers = new Array(slice.length);
for(var i=0; i<slice.length; i++){
byteNumbers[i] = slice.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
return new Blob(byteArrays, {
type: ''
});
}
function toExcel(target, param){
var filename = null;
var rows = null;
var worksheet = 'Worksheet';
if (typeof param == 'string'){
filename = param;
} else {
filename = param['filename'];
rows = param['rows'];
worksheet = param['worksheet'] || 'Worksheet';
}
var dg = $(target);
var uri = 'data:application/vnd.ms-excel;base64,'
, template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body>{table}</body></html>'
, base64 = function (s) { return window.btoa(unescape(encodeURIComponent(s))) }
, format = function (s, c) { return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; }) }
var table = toHtml(target, rows);
var ctx = { worksheet: worksheet, table: table };
var data = base64(format(template, ctx));
if (window.navigator.msSaveBlob){
var blob = b64toBlob(data);
window.navigator.msSaveBlob(blob, filename);
} else {
var alink = $('<a style="display:none"></a>').appendTo('body');
alink[0].href = uri + data;
alink[0].download = filename;
alink[0].click();
alink.remove();
}
}
$.extend($.fn.datagrid.methods, {
toHtml: function(jq, rows){
return toHtml(jq[0], rows);
},
toArray: function(jq, rows){
return toArray(jq[0], rows);
},
toExcel: function(jq, param){
return jq.each(function(){
toExcel(this, param);
});
},
print: function(jq, param){
return jq.each(function(){
print(this, param);
});
}
});
})(jQuery);
导出数据到excel
function exportExcel() {
var pageForm = {};
var orderList=invokeRemoteSync("networkMetadataAction","queryOLTNetworkMetadata",{pageForm:pageForm});//从后端查询数据到前端
var rows = orderList.listAll;
//var rows = $("#faultDataGrid").datagrid("getRows");
/*var bodyData = JSON.stringify(rows);
var a = bodyData.replace("areaName","aa");
var postData = {
data: a
};
var judge = invokeRemoteSync("networkMetadataAction","importToExcel",{postData:postData});*/
//$('#faultDataGrid').datagrid('hideColumn','edit');
$('#faultDataGrid').datagrid('toExcel',{
filename: 'excel名称.xls',
rows: rows,
worksheet: 'Worksheet'
}); // export to excel
}
导出数据到excel
function importExcel() {//导入
$('#popupDialog').dialog({
title: '标题',
width: 600,
height: 300,
closed: true,
cache: false,
modal: true,
content:"<div id=\"dw-eoms-import-importExcelView\"><div class=\"modal-header\"><h4 class=\"modal-title\">选择Excel文件</h4></div>\n" +
"<div class=\"modal-body\"><div class=\"row\"><form name=\"form1\" class=\"form-horizontal\" id=\"file_form\" action=\"/isa-web-fault/uploadExcel\" enctype=\"multipart/form-data\">\n" +
" <div class=\"form-group\"><div class=\"input-group\"> <input type=\"file\" onchange='importFile(this)' name=\"uploadFile\" class=\"upload\"><input type=\"hidden\" name=\"staffName\" id=\"staffName\" value=\"\"><input type=\"hidden\" name=\"staffId\" id=\"staffId\" value=\"\">\n" +
" <input type=\"hidden\" name=\"index\" id=\"index\" value=\"\"><span class=\"input-group-btn\">\n" +
"<button id=\"dw-planImport-importExcelView-upload\" type=\"button\" class=\"btn btn-default\">\n" +
"<span>上传文件</span></button></span></div></div><span class=\"alert-warning\">仅支持xls、xlsx类型的文件</span></form></div></div>\n" +
"<div class=\"button-group\">\n" +
"<button type=\"button\" id=\"impactCancel\" class=\"btn btn-default\" data-dismiss=\"modal\">关闭</button>\n" +
"</div></div></div>"
});
$('#popupDialog').window('open');
$('#popupDialog').window('center');
$("#dw-planImport-importExcelView-upload").on("click", function () {
var path = document.all.uploadFile.value;
var fileName = path.substr(path.lastIndexOf('\\') + 1, (path.length - path.lastIndexOf("\\")));
if (fileName.indexOf('.') == -1 || path.indexOf(':') == -1) {
$.messager.alert("错误","请先选择导入文件!","info");
return;
}
//验证文件格式
var fileType = (fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length)).toLowerCase();
if (fileType != 'xlsx' && fileType != 'xls') {
$.messager.alert("错误","文件格式不正确!","info");
return false;
}
if (!obj.files) {
return;
}
var f = obj.files[0];
var reader = new FileReader();
reader.onload = function (e) {
var data = e.target.result;
if (rABS) {
wb = XLSX.read(btoa(fixdata(data)), { //手动转化
type: 'base64'
});
} else {
wb = XLSX.read(data, {
type: 'binary'
});
}
// console.log(JSON.stringify(wb.Sheets[0]))
//wb.SheetNames[0]是获取Sheets中第一个Sheet的名字
//wb.Sheets[Sheet名]获取第一个Sheet的数据
//document.getElementById("demo").innerHTML = JSON.stringify(XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]));
console.log(JSON.stringify(XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])));
var jsonStr = JSON.stringify(XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]));
jsonStr = jsonStr.replaceAll("名称1","objName");
jsonStr = jsonStr.replaceAll("名称2","remoteMountainousAreas");
jsonStr = jsonStr.replaceAll("名称3","outdoorMinicomputer");
var objs = eval(jsonStr);
console.log(objs);
/*var arr = [];
for (var j = 0;j<objs.length;j++){
var obj = {};
obj.areaName = objs[j];
}*/
/*var pageForm;
var orderList=invokeRemoteSync("networkMetadataAction","queryOLTNetworkMetadata",{pageForm:pageForm});*/
var misObjName = invokeRemoteSync("networkMetadataAction","insertSetting",{objs:objs});//后端对数据库进行修改
if (misObjName.length > 0){
$.messager.alert("错误",misObjName+"网元设备不存在!","info");
}else if (misObjName.length == 0){
$.messager.alert("成功","上传文件成功!","info");
$('#popupDialog').window('close');
}
};
if (rABS) {
reader.readAsArrayBuffer(f);
} else {
reader.readAsBinaryString(f);
}
});
$("#impactCancel").on("click", function () {
$('#popupDialog').window('close');
});
}
function importFile(fileData) {
obj = fileData;
}
String.prototype.replaceAll = function(s1,s2){
return this.replace(new RegExp(s1,"gm"),s2);
}
function fixdata(data) { //文件流转BinaryString
var o = "",
l = 0,
w = 10240;
for (; l < data.byteLength / w; ++l) o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w,
l * w + w)));
o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w)));
return o;
}
导入EXCEL数据的DAO层代码
public String insertSetting(Map map) {
List list = (List) map.get("objs");
String faultObjName = "";
for (int i = 0;i<list.size();i++){
Map obj = (Map) list.get(i);
if (obj.get("objName") instanceof String == false){
obj.put("objName",obj.get("objName").toString());
}
if (obj.get("remoteMountainousAreas").equals("是")){
obj.put("remoteMountainousAreas","1");
}else if (obj.get("remoteMountainousAreas").equals("否")){
obj.put("remoteMountainousAreas","0");
}
if (obj.get("outdoorMinicomputer").equals("是")){
obj.put("outdoorMinicomputer","1");
}else if (obj.get("outdoorMinicomputer").equals("否")){
obj.put("outdoorMinicomputer","0");
}
String sql = "update MAINTAIN_MODEL_OBJECT MMO set MMO.REMOTE_MOUNTAINOUS_AREAS=:remoteMountainousAreas,MMO.OUTDOOR_MINICOMPUTER = :outdoorMinicomputer where MMO.OBJECT_NAME=:objName ";
int count = super.update(sql,obj);
if (count == 0){
faultObjName = faultObjName+MapUtils.getString(obj,"objName")+",";
}
}
if (faultObjName.length() > 0){
faultObjName = faultObjName.substring(0,faultObjName.length()-1);
}
return faultObjName;
}