实现点击导出表格中的数据为excel文件 (React + Nest.js)

138 阅读1分钟

Nest.js

  1. 引入依赖包 :npm i exceljs
  2. 创建模块 :nest g resource export
  3. export.controller.ts
@Get('excel/:type')
async exportToExcel(@Res() res: Response) {
    // data是一个数组,数组元素为对象
    // 例如,[{name: 'Tom', age: 12}]
    const data = [];
    const fileName = 'example-table'
    await this.exportService.exportToExcel(data, res, fileName);
}
  1. 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>;
      });
    });

    // 设置 HTTP 响应头
    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

  1. 引入依赖包 :npm i axios
  2. 编写一个按钮触发下载
  3. 编写方法触发下载
import axios from 'axios';

export const exportDataExcel = async (type: string) => {
  try {
    // 发送 GET 请求到后端获取数据
    const response = await axios.get(`http://localhost:5000/export/excel/${type}`, {
      responseType: 'blob' // 设置响应类型为 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);
  }
};