环境
- node: v12.16.1
- “koa”: “^2.8.1”
- “koa-body”: “^4.1.1”
- “exceljs”: “^4.0.1”
示例
koa_excel.js
const koa = require('koa');
const koaBody = require('koa-body');
const fs = require('fs');
const ExcelJS = require('exceljs')
const APP = new koa();
APP.use(koaBody({
jsonLimit: "8MB", // default: 56kb, change: 8MB
textLimit: "8MB", // default: 56kb, change: 8MB
formLimit: "8MB", // default: 56kb, change: 8MB
multipart: true
}));
const PAGE = `
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>下载示例</title>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.20.0-0/axios.min.js"></script>
</head>
<body>
<div>
<a href="/download">GET下载</a>
<span>引起地址栏变更的GET方式请求,不能用ajax的GET请求</span>
</div>
<div>
<button type="button" οnclick="download('blob')">POST下载(返回blob)</button>
<span>ajax POST请求,返回blob</span>
</div>
<div>
<button type="button" οnclick="download('json')">POST下载(返回json)</button>
<span>ajax POST请求,返回json</span>
</div>
<script>
function download(response_type){
axios({
method: "post",
url: "/download",
data: {
response_type: response_type
},
responseType: response_type
}).then(response => {
console.log(response)
let url=null;
if ('blob'===response_type) {
url = window.URL.createObjectURL(response.data);
console.log(url);
} else if('json'===response_type) {
url = window.URL.createObjectURL(new Blob([new Uint8Array(response.data.content.data)]));
console.log(url);
}
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'excel_demo.xlsx');
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}).catch(function (error) { // 请求失败处理
alert(error);
});
}
</script>
</body>
</html>`
APP.use(async ctx => {
console.log(ctx)
if (ctx.path === '/' && ctx.request.method === 'GET') {
ctx.body = PAGE
} else if (ctx.path === '/download') {
if (ctx.request.method === 'GET') {
ctx.response.attachment("excel_demo.xlsx")
ctx.body = fs.createReadStream('excel_demo.xlsx')
} else if (ctx.request.method === 'POST') {
const workbook = new ExcelJS.Workbook() //creating workbook
const worksheet = workbook.addWorksheet('sheet1') //creating worksheet
// add column headers
worksheet.columns = [
{ header: 'Album', key: 'album' },
{ header: 'Year', key: 'year' }
];
// add row using keys
worksheet.addRow({ album: "Taylor Swift", year: 2006 });
// add rows the dumb way
worksheet.addRow(["Fearless", 2008]);
// add an array of rows
const rows = [
["Speak Now", 2010],
{ album: "猎户星座", year: 2017 }
];
worksheet.addRows(rows);
// Write to local, File
await workbook.xlsx.writeFile("excel_demo.xlsx")
// Write to memory, buffer
const buffer = await workbook.xlsx.writeBuffer()
console.log('ctx.request.body: ', ctx.request.body)
if ('blob' === ctx.request.body.response_type) {
ctx.body = buffer
} else if ('json' === ctx.request.body.response_type) {
// object will be convert to json
ctx.body = {
status: 'success',
content: buffer
}
}
console.log('done')
}
}
});
APP.listen(5000)
console.log('start')