项目参考:
function ExporterExcel(dataTable, exportName) {
//获取Datagride的列
var rows = $(dataTable).datagrid('getRows');
var columns = $(dataTable).datagrid("options").columns[0];
var oXL = new ActiveXObject("Excel.Application"); //创建AX对象excel
var oWB = oXL.Workbooks.Add(); //获取workbook对象
var oSheet = oWB.ActiveSheet; //激活当前sheet
//设置工作薄名称
oSheet.name = exportName;
//设置表头
for (var i = 0; i < columns.length; i++) {
oSheet.Cells(1, i + 1).value = columns[i].title;
}
//设置内容部分
for (var i = 0; i < rows.length; i++) {
//动态获取每一行每一列的数据值
for (var j = 0; j < columns.length; j++) {
oSheet.Cells(i + 2, j + 1).value = rows[i][columns[j].field];
}
}
oXL.Visible = true; //设置excel可见属性
}
function SaveExcel(dataTable) {
var data = $(dataTable).datagrid('getExcelXml', { title: 'datagrid import to excel' });
var url = 'datagrid-to-excel.ashx';
$.ajax({ url: url, data: { data: data }, type: 'POST', dataType: 'text',
success: function (fn) {
alert('导出excel成功!');
window.location = fn; //执行下载操作
},
error: function (xhr) {
alert('动态页有问题\nstatus:' + xhr.status + '\nresponseText:' + xhr.responseText)
}
});
return false;
}
/**
Jquery easyui datagrid js导出excel
修改自extgrid导出excel
* allows for downloading of grid data (store) directly into excel
* Method: extracts data of gridPanel store, uses columnModel to construct XML excel document,
* converts to Base64, then loads everything into a data URL link.
*
* @author Animal
*
*/
$.extend($.fn.datagrid.methods, {
getExcelXml: function (jq, param) {
var worksheet = this.createWorksheet(jq, param);
//alert($(jq).datagrid('getColumnFields'));
var totalWidth = 0;
var cfs = $(jq).datagrid('getColumnFields');
for (var i = 1; i < cfs.length; i++) {
totalWidth += $(jq).datagrid('getColumnOption', cfs[i]).width;
}
//var totalWidth = this.getColumnModel().getTotalWidth(includeHidden);
return '' + //xml申明有问题,以修正,注意是utf-8编码,如果是gb2312,需要修改动态页文件的写入编码
''+
'' +
'' + param.title + ' 15.00 ' +
'' +
'' + worksheet.height + ' ' +
'' + worksheet.width + ' ' +
'False ' +
'False ' +
' ' +
'' +
'' +
' ' +
' ' +
'' +
' ' +
' ' +
' ' +
' ' +
' ' +
' ' +
' ' +
' ' +
' ' +
'' +
' ' +
' ' +
' ' +
' ' +
' ' +
'' +
' ' +
' ' +
' ' +
' ' +
'' +
' ' +
' ' +
'' +
' ' +
' ' +
'' +
' ' +
' ' +
'' +
' ' +
' ' +
'' +
' ' +
' ' +
'' +
' ' +
' ' +
'' +
' ' +
' ' +
'' +
' ' +
' ' +
' ' +
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 cfs = $(jq).datagrid('getColumnFields');
var colCount = cfs.length;
// var colOption = [];
for (var i = 0; i < colCount; i++) {
if (cfs[i] != '') {
var w = $(jq).datagrid('getColumnOption', cfs[i]).width;
//colOption.push($(jq).datagrid('getColumnOption', cfs[i]));
totalWidthInPixels += w;
if (cfs[i] === "") {
cellType.push("None");
cellTypeClass.push("");
++visibleColumnCountReduction;
}
else {
colXml += ' ';
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 = '' +
'' +
' ' +
' ' +
'' +
colXml +
'' +
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++) {
var fields = cfs;
var i = 0,
j = 0,
temp = {};
for (i; i < rows.length; i++) {
var row = rows[i];
j = 0;
for (j; j < fields.length; j++) {
var field = fields[j];
var option = $(jq).datagrid("getColumnOption", field);
var tf = temp[field];
if (!tf) {
tf = temp[field] = {};
if (option.mergeCell) {
temp[field].mergeCell = true;
}
tf[row[field]] = [i];
} else {
var tfv = tf[row[field]];
if (tfv) {
tfv.push(i);
} else {
tfv = tf[row[field]] = [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 = 0; j < fields.length; j++) {
//if ((cm.getDataIndex(j) != '')
if (temp[fields[j]].mergeCell) {
if (cfs[j] != '') {
//var v = r[cm.getDataIndex(j)];
var v = r[cfs[j]];
if (cellType[k] !== "None") {
if (i == temp[fields[j]][r[cfs[j]]][0]) {
t += '';
if (cellType[k] == 'DateTime') {
t += v.format('Y-m-d');
} else {
t += v;
}
t += ' ';
}
}
k++;
}
} else {
if (cfs[j] != '') {
//var v = r[cm.getDataIndex(j)];
var v = r[cfs[j]];
if (cellType[k] !== "None") {
t += '';
if (cellType[k] == 'DateTime') {
t += v.format('Y-m-d');
} else {
t += v;
}
t += ' ';
}
k++;
}
}
}
t += ' ';
}
result.xml = t + ' ' +
'' +
'' +
' ' +
' ' +
' ' +
' ' +
' ' +
'' +
'Blank ' +
'1 ' +
'32767 ' +
' ' +
'600 ' +
' ' +
' ' +
' ' +
'False ' +
'False ' +
' ' +
' '+
''+
'9000 '+
'19340 '+
'False '+
'False '+
' ';
return result;
}
});
/**
* author ____′↘夏悸
* create date 2012-11-5
*
**/
$.extend($.fn.datagrid.methods, {
autoMergeCells: function (jq, fields) {
return jq.each(function () {
var target = $(this);
if (!fields) {
fields = target.datagrid("getColumnFields");
}
var rows = target.datagrid("getRows");
var i = 0,
j = 0,
temp = {};
for (i; i < rows.length; i++) {
var row = rows[i];
j = 0;
for (j; j < fields.length; j++) {
var field = fields[j];
var option = target.datagrid("getColumnOption", field);
var tf = temp[field];
if (!tf) {
tf = temp[field] = {};
if (option.mergeCell) {
temp[field].mergeCell = true;
}
tf[row[field]] = [i];
} else {
var tfv = tf[row[field]];
if (tfv) {
tfv.push(i);
} else {
tfv = tf[row[field]] = [i];
}
}
}
}
$.each(temp, function (field, colunm) {
$.each(colunm, function () {
var group = this;
if (group.length > 1) {
if (colunm.mergeCell) {
var before,
after,
megerIndex = group[0];
for (var i = 0; i < group.length; i++) {
before = group[i];
after = group[i + 1];
if (after && (after - before) == 1) {
continue;
}
var rowspan = before - megerIndex + 1;
if (rowspan > 1) {
target.datagrid('mergeCells', {
index: megerIndex,
field: field,
rowspan: rowspan
});
}
if (after && (after - before) != 1) {
megerIndex = after;
}
}
}
}
});
});
});
}
});
<%@ WebHandler Language="C#" Class="datagrid_to_excel" %>
using System;
using System.Web;
using System.IO;
using System.Text;
public class datagrid_to_excel : IHttpHandler {
public void ProcessRequest (HttpContext context) {
//context.Response.ContentType = "text/plain";
//context.Response.Write("Hello World");
string fn = DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".xls";
string data = context.Request.Form["data"];
File.WriteAllText(context.Server.MapPath("~/UploadFiles/"+fn), data, Encoding.UTF8);
context.Response.Write("../UploadFiles/" + fn);
}
public bool IsReusable {
get {
return false;
}
}
}
保存//导出Excel事件SaveExcel($('#datagrid'));
注意:如果在使用中报“从客户端(exportContent=" 在Web.Config文件中的配置节之前加上如下一句配置就可以了 效果如图:请忽略掉无关的内容,谢谢