前端js导出数据为Excel
主要接口:
add_sheet(Excel名称,表头字段, 表数据 )
export( 导出文件名称 )
注意:调用多次add_sheet就会生成一个多页Excel
示例代码:
excel.add_sheet('test',['姓名','电话号码'],[['xt','13333333'],['xe','8888888888']]);
excel.add_sheet('第二表格',['姓名','电话号码'],[['xt','166666'],['xe','66666']]);
excel.export( '哈哈哈');
主要代码如下:
var excel = {version:0.01,sheets:[]}; var tmplWorkbookXML = ''
+''
+ 'ZhangYe {created} '
+ ''
+ ''
+ ''
+ ''
+ '{worksheets}'
, tmplWorksheetXML = '
{rows}
' , tmplCellXML = '{data}'; |
excel.add_sheet = function( _title, _fields, _data ){
var _t = {};
_t.title = _title;
_t.fields = _fields;
_t.data = _data;
excel.sheets.push( _t );
}
excel.format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
excel.base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
excel.export = function( _title ) {
if( !this.sheets || this.sheets.length < 1 )
return false;
var ctx = "";
var workbookXML = "";
var worksheetsXML = "";
var rowsXML = "";
var rowdata = null;
for (var i = 0; i < this.sheets.length; i++) {
this.sheets[i].data.unshift( this.sheets[i].fields );
for (var j = 0; j < this.sheets[i].data.length; j++) {
rowsXML += '';
for (var k = 0; k < this.sheets[i].data[j].length; k++) {
var dataValue = this.sheets[i].data[j][k];
ctx = { attributeStyleID:''
, nameType:'String'
, data: (dataValue)? dataValue : ''
, attributeFormula:''
};
rowsXML += this.format(tmplCellXML, ctx);
}
rowsXML += ''
}
ctx = {rows: rowsXML, nameWS: this.sheets[i].title || 'Sheet' + i};
worksheetsXML += this.format(tmplWorksheetXML, ctx);
rowsXML = "";
}
ctx = {created: (new Date()).getTime(), worksheets: worksheetsXML};
workbookXML = this.format(tmplWorkbookXML, ctx);
if( _title ) _title + '.xls';
var download = _title || 'Workbook.xls';
var blob = new Blob([ workbookXML], {
type: "application/vnd.ms-excel;charset=charset=utf-8"
});
saveAs(blob, download);
}
使用到库有: