Nest.js
- 引入依赖包 :
npm i exceljs
- 创建模块 :
nest g resource export
export.controller.ts
@Get('excel/:type')
async exportToExcel(@Res() res: Response) {
const data = [];
const fileName = 'example-table'
await this.exportService.exportToExcel(data, res, fileName);
}
export.service.ts
const headerName = {
name: '姓名',
age: '年龄',
}
async exportToExcel(data: any[], res: Response, fileName: string) {
const workbook = new ExcelJS.Workbook();
const worksheet = workbook.addWorksheet('Sheet 1');
const headerStyle = {
font: { bold: true },
alignment: { vertical: 'middle', horizontal: 'center' }
};
const headers = Object.keys(data[0]);
const headerNames = headers.map((item) => headerName[item])
worksheet.addRow(headerNames);
worksheet.eachRow(row => {
row.font = headerStyle.font;
row.alignment = headerStyle.alignment as Partial<Alignment>;
});
data.forEach((record) => {
const row = [];
headers.forEach((header) => {
row.push(record[header]);
});
worksheet.addRow(row);
worksheet.eachRow(row => {
row.alignment = headerStyle.alignment as Partial<Alignment>;
});
});
res.setHeader(
'Content-Type',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
);
res.setHeader(
'Content-Disposition',
`attachment; filename=${fileName}.xlsx`,
);
await workbook.xlsx.write(res);
res.end();
}
React
- 引入依赖包 :
npm i axios
- 编写一个按钮触发下载
- 编写方法触发下载
import axios from 'axios';
export const exportDataExcel = async (type: string) => {
try {
const response = await axios.get(`http://localhost:5000/export/excel/${type}`, {
responseType: 'blob'
});
const url = window.URL.createObjectURL(new Blob([response.data]));
const a = document.createElement('a');
a.href = url;
a.download = `${type}-table.xlsx`;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
} catch (error) {
console.error('Error downloading file:', error);
}
};