vue3.0 将接口 json 数据导出为xlsx 文件

1,184 阅读1分钟

vue3.0 将接口 json 数据导出为.xlsx 文件

注意: 导出的数据应与页面的显示的一致
1.前置数据和配置
  • 页面 table 显示的 columns 配置
const columns = [
  {
    title: "计划名称",
    dataIndex: "planName",
    key: "planName",
    width: "150px",
  },
  {
    title: "计划开始时间",
    dataIndex: "planStartDate",
    key: "planStartDate",
    customRender: ({ text }) =>
      text ? moment(text).format(DateFormatEnum.YMD) : "--",
  },
  // ...
];
  • 接口返回的数据结构
{
  "data": [
    { "planName": "计划1", "planStartDate": "2021-06-22 17:27:36" },
    { "planName": "计划2", "planStartDate": "2021-06-22 17:27:54" }
    //...
  ]
}
2. 实现
export function json2xlsx(props) {
  // columns: table的配置
  // list: 接口返回的数据
  const { columns, list, filename = "data" } = props;

  // 搜集单元格宽度, 中文标题, 及自定义内容
  const map = {};

  columns.forEach((o) => {
    map[o.key] = {
      title: o.title,
      customRender: o.customRender,
      width: Number.parseFloat(o.width) || 120, // Number.parseFloat('100px') => 100
    };
  });

  // 收集单元格宽度
  const cellWidth = [];

  // 转换接口返回的数据
  // 转换完成后data的数据结构为: [{ 计划名称: 计划1, 计划开始时间: 2021-06-22 }, { 计划名称: 计划2, 计划开始时间: 2021-06-22 }]
  const data = list.map((o: T) => {
    const item = {};
    Object.keys(o).forEach((k) => {
      if (map[k]) {
        // 设置要显示的数据
        item[map[k].title] = map[k].customRender
          ? map[k].customRender({ text: o[k] })
          : o[k];
        // 搜集单元格宽度
        cellWidth.push({ wpx: map[k].width });
      }
    });
    return item;
  });

  // 创建sheet
  const ws = XLSX.utils.json_to_sheet(data);
  // 设置每列的宽度
  ws["!cols"] = cellWidth;
  // 设置第一行的高度
  ws["!rows"] = [{ hpx: 30 }];
  // 创建工作簿
  const wb = XLSX.utils.book_new();
  // 将sheet添加到工作簿中, 并命名sheet
  XLSX.utils.book_append_sheet(wb, ws, "sheet");

  // 将工作簿导出为xlsx文件
  XLSX.writeFile(wb, `${filename}.xlsx`);
}