Vue3.0 exports the JSON interface data as an. XLSX file

Note: The exported data should be consistent with the page display
1. Pre-configuration data
  • The columns configuration shown on the table page
const columns = [
  {
    title: "Project Name".dataIndex: "planName".key: "planName".width: "150px"}, {title: "Project Start Time".dataIndex: "planStartDate".key: "planStartDate".customRender: ({ text }) = >
      text ? moment(text).format(DateFormatEnum.YMD) : "--",},// ...
];
Copy the code
  • The data structure returned by the interface
{
  "data": [{"planName": Plan "1"."planStartDate": "The 2021-06-22 17:27:36" },
    { "planName": "Plan 2"."planStartDate": "The 2021-06-22 17:27:54" }
    / /...]}Copy the code
2. Implement
export function json2xlsx(props) {
  // Columns: table configuration
  // list: data returned by the interface
  const { columns, list, filename = "data" } = props;

  // Collect cell width, Chinese title, and custom content
  const map = {};

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

  // Collect cell width
  const cellWidth = [];

  // Convert the data returned by the interface
  [{plan name: Plan 1, plan start time: 2021-06-22}, {plan name: Plan 2, plan start time: 2021-06-22}]
  const data = list.map((o: T) = > {
    const item = {};
    Object.keys(o).forEach((k) = > {
      if (map[k]) {
        // Set the data to display
        item[map[k].title] = map[k].customRender
          ? map[k].customRender({ text: o[k] })
          : o[k];
        // Collect cell width
        cellWidth.push({ wpx: map[k].width }); }});return item;
  });

  / / create a sheet
  const ws = XLSX.utils.json_to_sheet(data);
  // Set the width of each column
  ws[! "" cols"] = cellWidth;
  // Set the height of the first line
  ws[! "" rows"] = [{ hpx: 30 }];
  // Create a workbook
  const wb = XLSX.utils.book_new();
  // Add sheet to the workbook and name it
  XLSX.utils.book_append_sheet(wb, ws, "sheet");

  // Export the workbook as an XLSX file
  XLSX.writeFile(wb, `${filename}.xlsx`);
}
Copy the code