koa2+vue3通过exceljs实现数据导出excel文档

  1. 服务端安装exceljs依赖
npm i exceljs
  1. 服务端实现代码
    1. 实现导出excel文件工具方法
const ExcelJS = require('exceljs');
/**
 * @description: 导出excel文件
 * @param {*} fileHeader  导出的表头
 * @param {*} data 导出的数据
 * @param {*} ctx 上下文对象
 * @return {*}
 */
async function exportExcel(fileHeader, data, ctx){
  const workbook = new ExcelJS.Workbook();
  const sheet = workbook.addWorksheet();
  sheet.columns = fileHeader.map((item,index)=>{
    return {
      header: item.header,
      key: item.key,
      width: item.width||25,
    }
  })
  data.forEach((item,index)=>{
    sheet.addRow(item);
  })
  
  // 生成Excel文件
  const buffer = await workbook.xlsx.writeBuffer();

  ctx.status = 200;
  ctx.set('Content-Type', 'application/vnd.openxmlformats');
  ctx.attachment('example.xlsx');
  ctx.body = buffer;

}

module.exports = exportExcel;
b. 使用案例
await exportExcel(
      [
        { header: "Name", key: "name", width: 20 },
        { header: "Age", key: "age", width: 10 },
        { header: "Email", key: "email" },
      ],
      [
        { name: "测试数据1", age: 320, email: "alice@example.com" },
        { name: "测试数据2", age: 330, email: "alice@example.com" },
        { name: "测试数据3", age: 340, email: "alice@example.com" },
      ],
      ctx
    );
  1. 客户端代码实现
    1. 创建下载excel工具方法
/**
 * @description: 下载excel方法
 * @param {String} filename
 * @param {Blob} blob
 */
async function exportExcel(filename = "导出文件", blob: Blob) {
  const url = window.URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.href = url;
  link.download = filename; // 设置下载的文件名
  document.body.appendChild(link); // 需要添加到DOM中才能生效
  link.click();
  document.body.removeChild(link);
  window.URL.revokeObjectURL(url); // 释放内存
}

export default exportExcel;
b. 接口请求方法封装
export const exportTableApi = (url: string, params: any = {}) => {
  return http.get<any>(url + "/export-to-excel", params, {
    headers: {
      Accept:
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    },
    **responseType: "blob",**
  });
};
c. 使用案例
/**
   * @description 导出表格数据
   * @return void
   * */
  const exportData = async (apiUrl, params) => {
    const data = await exportTableApi(apiUrl, params);
    const blob = new Blob([data as any], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    });
    exportExcel(tableName, blob);
  };
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值