前言:對于一個后臺管理系統(tǒng)而言,可視化展現(xiàn)數(shù)據(jù)是必不可少的一部分,而將這些數(shù)據(jù)導(dǎo)出為Excel可打開的文件的需求可很常見,如果前端把所有數(shù)據(jù)一次性拿到的話,這個需求可以在前端完成,但是對于做了分頁處理的后臺管理系統(tǒng)而言,前端并不是一次性拿到所有數(shù)據(jù),而這時需要一次性導(dǎo)出所有表格數(shù)據(jù)(包括還沒有加載到前端的數(shù)據(jù)),那么肯定是后臺操作比較好。
exceljs
直接上代碼,還是很好懂的。測試數(shù)據(jù):
let data = [{
id: 1,
name: '張三',
birth: new Date(1994,2,14)
},{
id: 2,
name: '李四',
birth: new Date(1995,8,24)
},{
id: 3,
name: '王五',
birth: new Date(1991,10,10)
},{
id: 4,
name: '周六',
birth: new Date(1992,7,1)
}];
node.js代碼:
const Excel = require('exceljs');
const http = require('http');
const url = require('url');
http.createServer( async (req, res) => {
if(req.method == 'GET' && req.url == '/xlsx') {
res.writeHead(200, {
"Content-Type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", //xlsx 文件制定類型
"Access_Control-Allow-Origin": "*",
"Content-Disposition": "attachment; filename=" + new Buffer('測試excel.xlsx').toString('binary'), // 設(shè)置文件名稱
});
try {
const workbook = new Excel.Workbook(); // 創(chuàng)建一個Workbook對象
const worksheet = workbook.addWorksheet('My Sheet'); // 創(chuàng)建一個worksheet并命名
worksheet.columns = [ // 設(shè)置列表屬性
{ header: '編號', key: 'id', width: 8 },
{ header: '姓名', key: 'name', width: 12 },
{ header: '生日', key: 'birth', width: 25 },
{ header: '隱藏列', key: 'hidden', width: 20 }
];
// 行、列均從1開始計數(shù),header作為第一行數(shù)據(jù)
worksheet.addRows(data); // 寫入json數(shù)組數(shù)據(jù)
worksheet.addRow([5,'朱八',new Date(1999,9,6), 12345]); // 單獨(dú)添加一行數(shù)據(jù)
const hiddenCol = worksheet.getColumn('hidden'); // 獲取列
hiddenCol.hidden = true; // 隱藏列
const row5 = worksheet.getRow(5); // 獲取第5行
row5.height = 50; // 設(shè)置第5行的高度
await workbook.xlsx.write(res); // 寫入數(shù)據(jù)
res.end();
} catch(error) {
console.log(error);
res.end('error');
}
}
}).listen(8000,'127.0.0.1');
可以看到能夠很方便的設(shè)置寬高,是否隱藏等屬性,操作數(shù)據(jù)庫也挺自然,下圖是最后的效果:

測試excel.png
除此之外,exceljs對于某行,某列,某個具體的單元格都可以靈活的設(shè)置其樣式(是否加粗,寬高,邊距,顏色等等)或者統(tǒng)計行列,合并單元格等等,是非常優(yōu)秀的一個庫。