React + exceljs 導出Excel文件


1.前端導出 excel 文件基本步驟

1.1 引入

import Excel from "exceljs";

1.2 初始化工作簿

const workbook = new Excel.Workbook();

1.3 設置工作簿屬性

workbook.creator = "admin";
workbook.lastModifiedBy = "admin";
workbook.created = new Date();
workbook.modified = new Date();

1.4 設置表頭

worksheet.columns = [
  { header: 'Id', key: 'id', width: 10 },
  { header: 'Name', key: 'name', width: 32 },
  { header: 'D.O.B.', key: 'DOB', width: 10, outlineLevel: 1 }
];

1.5 添加表格數據

const row = sheet.getRow(1);
  row.eachCell((cell, rowNumber) => {
    sheet.getColumn(rowNumber).alignment = {
      vertical: "middle",
      horizontal: "center",
    };
  });

1.6 導出表格

// 將表格數據轉為二進制
workbook.xlsx.writeBuffer().then((buffer) => {
    writeFile(`${execlTitle}.xlsx`, buffer);
});
      
// 將二進制轉為Excel並下載
const writeFile = (fileName, content) => {
    let a = document.createElement("a");
    let blob = new Blob([content], { type: "text/plain" });

    a.download = fileName;
    a.href = URL.createObjectURL(blob);

    a.click();
};

2. excel導出組件完整代碼

import React, { useState, useEffect } from "react";
import { Button } from "antd";
import "antd/dist/antd.css";
import Excel from "exceljs";

/**
  text?: string // 下載按鈕內文字
  icon?: string // 按鈕 icon
  size?: string // 按鈕尺寸
  type?: string // 按鈕類型
  execlTitle?: string // 導出execl文件名
  tableColumns: [] // 表頭
  selectedUrl: string // 接口地址url
 */

const TableDownload = ({
  size = "default",
  text = "導出",
  type = "default",
  icon = "download",
  selectedUrl,
  execlTitle = "表格數據",
}) => {
  const [isLoading, setLoading] = useState(false);
  const [tableRows, setTableData] = useState([]);
  const [tableColumns, setTableColumns] = useState([]);

  useEffect(() => {
    setLoading(true);
    fetch(selectedUrl)
      .then((response) => response.json())
      .then(({ data }) => {
        setTableColumns(data && data.columns);
        setTableData(data && data.rows);
        setTimeout(() => {
          setLoading(false);
        }, 2000);
      });
  }, [selectedUrl]);

  // 執行下載表格
  const fetchTableDatas = () => {
    // 初始化 創建工作簿
    const workbook = new Excel.Workbook();
    // 設置工作簿屬性
    workbook.creator = "admin";
    workbook.lastModifiedBy = "admin";
    workbook.created = new Date();
    workbook.modified = new Date();

    // 添加工作表
    let sheet = workbook.addWorksheet("sheet");

    let columns = [];
    // 表頭格式化
    tableColumns.map((item) => {
      columns.push({
        header: item.title,
        key: item.key || item.dataIndex,
        width: parseInt(item.width / 6, 10) || 40,
      });
      return true;
    });

    // 添加表頭
    sheet.columns = columns;

    if (Array.isArray(tableRows)) {
      // 添加表格數據
      sheet.addRows(tableRows);

      // 設置每一列樣式 居中
      const row = sheet.getRow(1);
      row.eachCell((cell, rowNumber) => {
        sheet.getColumn(rowNumber).alignment = {
          vertical: "middle",
          horizontal: "center",
        };
      });

      // 將表格數據轉為二進制
      workbook.xlsx.writeBuffer().then((buffer) => {
        writeFile(`${execlTitle}.xlsx`, buffer);
      });
    } else {
      alert("下載失敗");
    }
  };

  // 將二進制轉為Excel並下載
  const writeFile = (fileName, content) => {
    let a = document.createElement("a");
    let blob = new Blob([content], { type: "text/plain" });

    a.download = fileName;
    a.href = URL.createObjectURL(blob);

    a.click();
  };

  return (
    <div style={{ padding: 10, margin: 10, border: "1px solid red" }}>
      <Button
        type={type}
        icon={icon || ""}
        size={size}
        loading={isLoading}
        onClick={fetchTableDatas}
      >
        {isLoading ? "正在導出" : text}
      </Button>
    </div>
  );
};

export default TableDownload;

3. 組件使用

import TableDownload from "./TableDownload";

<TableDownload
  text="導出"
  execlTitle="表格數據"
  selectedUrl="/api/tableData.json"
  icon="download"
/>

其中,接口請求的tableData.json數據為:

{
  "data": {
    "total": 3,
    "columns": [
      {
        "dataIndex": "name",
        "title": "姓名"
      },
      {
        "dataIndex": "age",
        "title": "年齡"
      }
    ],
    "rows": [
      {
        "id": 1,
        "name": "tom",
        "age": "18"
      },
      {
        "id": 2,
        "name": "jim",
        "age": "25"
      },
      {
        "id": 3,
        "name": "tim",
        "age": "25"
      }
    ]
  }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM