xlsx.full.min.js
或者核心文件xlsx.core.min.js
都可以xlsxStyle.core.min.js
可以从XLSX-Style-Utils的源码中下载:XLSX
,所以XLSX-Style-Utils的作者对XLSX-Style进行了优化,将变量名改成了xlsxStyle
,js-xlsx的变量名还是XLSX
xlsxStyle.utils.js
,在Github上下载:FileSaver.js
,GitHub:https://github.com/eligrey/FileSaver.js代码如下:
<script type="text/javascript" src="./static/js/FileSaver.js"></script>
<script type="text/javascript" src="./static/js/xlsx.full.min.js"></script>
<script type="text/javascript" src="./static/js/xlsxStyle.core.min.js"></script>
<script type="text/javascript" src="./static/js/xlsxStyle.utils.js"></script>
代码如下:
var aoa1 = [
['姓名', '性别', '年龄', '注册时间'],
['张三', '男', 18, new Date()],
['李四', '女', 22, new Date()]
];
var aoa2 = [
['姓名', '性别', '年龄', '注册时间'],
['张五', '男', 38, new Date()],
['李六', '女', 42, new Date()]
];
代码如下:
// 转换为sheet
var sheet1 = XLSX.utils.aoa_to_sheet(aoa1);
var sheet2 = XLSX.utils.aoa_to_sheet(aoa2);
代码如下,转换函数见最后:
var Workbook = App.sheet2Workbook([{
sheetName: 'sheet1',
sheetData: sheet1,
},{
sheetName: 'sheet2',
sheetData: sheet2,
}]);
代码如下:
// setFontColorRGBOfRows 和 setFontColorRGBOfCols 是我根据源码添加的函数,原本只有对单个单元格和全部单元格的修改颜色函数
// xlsxStyle.utils.js源码写的比较清楚,有需要可自己修改
XSU.setFontColorRGBOfRows(Workbook, 'sheet1', "FF0000", 1);
XSU.setFontColorRGBOfCols(Workbook, 'sheet2', "00FF00", 'A');
XSU.setFontBoldOfRows(Workbook,'sheet1',true,1);
XSU.setFontBoldOfRows(Workbook,'sheet2',true,1);
代码如下,转换函数见最后:
// 导出
saveAs(App.Workbook2Blob(Workbook), '导出.xlsx');
/*
* @Description: 导出xlsx工具
* @Author: Andy Zhao
* @Date: 2021-02-18 15:26:57
* @LastEditors: Andy Zhao
* @LastEditTime: 2021-02-19 13:25:48
*/
var App = App || {}
App = ({
/**
* @description: sheet -> Workbook 支持多sheet
* @param {Array} sheets [{sheetData1, sheetName1}, ...]
* @return {Workbook}
*/
sheet2Workbook: function(sheets){
if (!Array.isArray(sheets)){
sheets = [sheets];
}
var workbook = {
SheetNames: [],
Sheets: {}
}
for (sheet of sheets){
sheet.sheetName = sheet.sheetName || 'sheet'+(workbook.SheetNames.length+1);
workbook.SheetNames.push(sheet.sheetName);
workbook.Sheets[sheet.sheetName] = sheet.sheetData;
}
return workbook;
},
/**
* @description: Workbook -> Blob
* @param {Workbook} workbook
* @return {Blob}
*/
Workbook2Blob: function(workbook){
var wopts = {
bookType: 'xlsx', // 要生成的文件类型
bookSST: false, // 是否生成Shared String Table,官方解释是,如果开启生成速度会下降,但在低版本IOS设备上有更好的兼容性
type: 'binary'
};
// 原本是XLSX.write, 需要样式则用xlsxStyle
var wbout = xlsxStyle.write(workbook, wopts);
var blob = new Blob([s2ab(wbout)], {type:"application/octet-stream"});
// 字符串转ArrayBuffer
function s2ab(s) {
var buf = new ArrayBuffer(s.length);
var view = new Uint8Array(buf);
for (var i=0; i!=s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
return buf;
}
return blob;
},
})