有需求就是将EasyUI Datagrid的数据导出为Excel且需要通用,因此本文使用将EasyUI Datagrid的数据转换成XML Post提交给java 后台代码如下:
$.extend($.fn.datagrid.methods, {
getExcelXml: function (jq, param) {
var worksheet = this.createWorksheet(jq, param);
//alert($(jq).datagrid('getColumnFields'));
var totalWidth = 0;
var cfsFro = $(jq).datagrid('getColumnFields',true);
var cfs1 = $(jq).datagrid('getColumnFields');
var cfs = cfsFro.concat(cfs1);
for (var i = 1; i < cfs.length; i++) {
totalWidth += $(jq).datagrid('getColumnOption', cfs[i]).width;
}
//var totalWidth = this.getColumnModel().getTotalWidth(includeHidden);
return '1.0" encoding="utf-8"?>' +//xml申明有问题,以修正,注意是utf-8编码,如果是gb2312,需要修改动态页文件的写入编码
'" xmlns:x=" urn:schemas-microsoft-com:office:excel" xmlns:o="urn:schemas-microsoft-com:office:office">' +
'' + param.title + '' +
'' +
'' + worksheet.height + '' +
'' + worksheet.width + '' +
'False ' +
'False ' +
'' +
'' +
'">' +
'" />' +
'" ss:Size=" 10" />' +
'' +
'1 " ss:LineStyle="Continuous" ss:Position="Top" />' +
'1 " ss:LineStyle="Continuous" ss:Position="Bottom" />' +
'1 " ss:LineStyle="Continuous" ss:Position="Left" />' +
'1 " ss:LineStyle="Continuous" ss:Position="Right" />' +
'' +
' ' +
' ' +
' ' +
'' +
'">' +
' ' +
' ' +
'" ss:Horizontal=" Center" />' +
'" />' +
'' +
'">' +
'1 " ss:Size="10" />' +
'" />' +
'" />' +
'' +
'">' +
'" />' +
'' +
'" ss:ID=" evendate">' +
'" />' +
'' +
'" ss:ID=" evenint">' +
'0 " />' +
'' +
'" ss:ID=" evenfloat">' +
'0.00 " />' +
'' +
'">' +
'" />' +
'' +
'" ss:ID=" odddate">' +
'" />' +
'' +
'" ss:ID=" oddint">' +
'0 " />' +
'' +
'" ss:ID=" oddfloat">' +
'0.00 " />' +
'' +
'' +
worksheet.xml +
'';
},
createWorksheet: function (jq, param) {
// Calculate cell data types and extra class names which affect formatting
var cellType = [];
var cellTypeClass = [];
//var cm = this.getColumnModel();
var totalWidthInPixels = 0;
var colXml = '';
var headerXml = '';
var visibleColumnCountReduction = 0;
var cfsFro = $(jq).datagrid('getColumnFields',true);
var cfs1 = $(jq).datagrid('getColumnFields');
var cfs = cfsFro.concat(cfs1);
var colCount = cfs.length;
for (var i = 1; i < colCount; i++) {
if (cfs[i] != '') {
var w = $(jq).datagrid('getColumnOption', cfs[i]).width;
totalWidthInPixels += w;
if (cfs[i] === "") {
cellType.push("None");
cellTypeClass.push("");
++visibleColumnCountReduction;
}
else {
colXml += '1 " ss:Width="130" />';
headerXml += '">' +
'">' + $(jq).datagrid('getColumnOption', cfs[i]).title + '' +
'" />' ;
cellType.push("String");
cellTypeClass.push("");
}
}
}
var visibleColumnCount = cellType.length - visibleColumnCountReduction;
var result = {
height: 9000,
width: Math.floor(totalWidthInPixels * 30) + 50
};
var rows = $(jq).datagrid('getRows');
// Generate worksheet header details.
var t = '' + param.title + ' ">' +
'' +
'" ss:RefersTo=" =\'' + param.title + '\'!R1:R2" />' +
'' +
'"1" x:FullColumns="1"' +
' ss:ExpandedColumnCount="' + (visibleColumnCount + 2) +
'" ss:ExpandedRowCount="' + (rows.length + 2) + '">' +
colXml +
'"1">' +
headerXml +
' ';
// Generate the data rows from the data in the Store
//for (var i = 0, it = this.store.data.items, l = it.length; i < l; i++) {
for (var i = 0, it = rows, l = it.length; i < l; i++) {
t += '';
var cellClass = (i & 1) ? 'odd' : 'even';
r = it[i];
var k = 0;
for (var j = 1; j < colCount; j++) {
//if ((cm.getDataIndex(j) != '')
if (cfs[j] != '') {
//var v = r[cm.getDataIndex(j)];
var v = r[cfs[j]];
if (cellType[k] !== "None") {
t += '' + cellClass + cellTypeClass[k] + ' ">' + cellType[k] + ' ">';
if (cellType[k] == 'DateTime') {
t += v.format('Y-m-d');
} else {
t += v;
}
t += '';
}
k++;
}
}
t += ' ';
}
result.xml = t + '' +
'' +
'' +
'1 " x:Orientation="Landscape" />' +
'" x:Margin=" 0.5" />' +
'0.5 " x:Right="0.5" x:Left="0.5" x:Bottom="0.8" />' +
'' +
' ' +
'' +
'Blank ' +
'1 ' +
'32767 ' +
' ' +
'600 ' +
'' +
' ' +
' ' +
'False ' +
'False ' +
'' +
'';
return result;
}
});
<form id='student_allStudent_formAction' action="url" method="post">//url Java后台的地址
<input id="ceName" name='ceName' type="hidden"/>
<input id="came" name='came' type="hidden"/>
form>
function OutputExcel() {
//getExcelXML有一个JSON对象的配置,配置项看了下只有title配置,为excel文档的标题
var data = $('#student_allStudent_table').datagrid('getExcelXml', { title: '全部学生' }); //获取datagrid数据对应的excel需要的xml格式的内容
console.log(data);
document.getElementById("ceName").value=data;
document.getElementById("came").value="excel";
document.getElementById("student_allStudent_formAction").submit();
}
"javascript:void(0);" class="easyui-linkbutton" iconCls="icon-redo" onclick="student_allStudent_obj.excle();">导出Excela>
student_allStudent_obj ={
excle: function () {
OutputExcel();
}
}
private String hf;
private String type;
public String getHf() {
return hf;
}
public void setHf(String hf) {
this.hf = hf;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String execute1() throws Exception {
// ServletActionContext.getResponse().reset();
// try {
// request.setCharacterEncoding("UTF-8");
// } catch (UnsupportedEncodingException e1) {
// // TODO Auto-generated catch block
// e1.printStackTrace();
// }
String exportname="grid";
try {
if(type.equals("excel"))
{
exportname+=".xls";
ServletActionContext.getResponse().setHeader("Content-disposition", "attachment; filename="+java.net.URLEncoder.encode(exportname, "UTF-8")+"");
ServletActionContext.getResponse().setContentType("application/msexcel;charset=utf-8");
}
else if(type.equals("word"))
{
exportname+=".doc";
ServletActionContext.getResponse().setHeader("Content-disposition", "attachment; filename="+java.net.URLEncoder.encode(exportname, "UTF-8")+"");
ServletActionContext.getResponse().setContentType("application/ms-word;charset=UTF-8");
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
PrintWriter out;
try {
out = ServletActionContext.getResponse().getWriter();
out.println(hf);
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
这样就能完成EasyUI Datagrid数据导出Excel