使用数据生成一个Excel表格供调用者下载。
/** * 下载模板 */ function C001() { return <> <Link href={s001}> <a> 下载模板 </a> </Link> <style jsx>{` a { color: blue; text-decoration: underline; } `}</style> </>; }
yarn add exceljs
import { Workbook } from 'exceljs';
const wb = new Workbook(); const ws = wb.addWorksheet('主要人物'); ws.columns = [{ header: '姓名', key: 'name' }, { header: '年龄', key: 'age' }, { header: '性别', key: 'sex' }]; const data = [{ name: '小召', age: 16, sex: 0 }, { name: '无忌', age: 20, sex: 1 }, { name: '赵敏', age: 19, sex: 0 }, { name: '周芷若', age: 18, sex: 0 }, { name: '张君宝', age: 108, sex: 1 }]; data.forEach((it) => { const row = ws.addRow({ ...it, sex: it.sex === 1 ? '男' : '女' }); const cell = row.getCell('sex'); cell.dataValidation = { type: 'list', allowBlank: true, formulae: ['"男,女"'] }; }); const filename = encodeURIComponent('倚天屠龙.xlsx'); res.setHeader('Content-Disposition', `attachment; filename=${filename}`); await wb.xlsx.write(res);