我正在使用 excel.js 将用户列表下载到 xlsx 文件中,但无法将 blob 转换为可读文件

问题描述 投票:0回答:1

api 获取用户,但是当我将 api 实现到前端时,response.data 未定义,我尝试了很多次,但结果是相同的

我想尝试将用户数据下载到excel表中,我正在使用excelJs,但无法这样做,所以我需要专家的帮助来指导我或建议我更简单的方法来下载xlsx中的用户数据

nodejs API

 export const getUserCSV = async (req, res) => {
  try {
     const users = await User.find({});

     const workbook = new exceljs.Workbook();

     const sheet = workbook.addWorksheet("users");

      const header = [
      { header: "Username", key: "userName", width: 20 },
      { header: "First Name", key: "firstName", width: 20 },
      { header: "Last Name", key: "lastName", width: 20 },
      { header: "Email", key: "email", width: 20 },
      { header: "Role", key: "role", width: 20 },
       ];

       sheet.columns = header;

      users.forEach((user) => {
       sheet.addRow(user.toObject()); // Ensure each user is converted to a plain object
       });

        sheet.getRow(1).eachCell((cell) => {
        cell.font = { bold: true };
      });

      // Set response headers
     res.setHeader("Content-Type", "text/csv");
     res.setHeader("Content-Disposition", "attachment; filename=users.csv");

     // Convert workbook to CSV and send as plain text
     workbook.csv
  .writeBuffer()
  .then((buffer) => {
    res.send(buffer.toString());
  })
  .catch((error) => {
    console.error(error);
    res.status(500).send("Internal Server Error");
  });
   } catch (error) {
   console.error("Error exporting users:", error);
    res.status(500).send({ message: "Internal server error" });
    }
   };

前端实现

    const handleExport = async () => {
     fetch("/api/user/get-user-csv")
      .then((response) => response.text())
       .then((data) => {
         console.log(data); // Log the received data to the console
         if (data !== undefined) {
           const blob = new Blob([data], { type: "text/csv;charset=utf-8" });
           fileSaver.saveAs(blob, "users.xlsx");
         } else {
          console.error("Error: CSV data is undefined");
         }
        })
       .catch((error) => {
    console.error("Error downloading CSV:", error);
        });
     };
express mern exceljs
1个回答
0
投票

从后端发送数据:-

const contentType = "application/vnd.ms-excel";
const fileName = `fileName.xlsx`;
const fileBuffer = await workbook.xlsx.writeBuffer();

res.set({
  "Content-Type": contentType,
  "Content-Disposition": `attachment; filename=${fileName}`,
  "Content-Length": fileBuffer.length,
});

res.status(200).send(fileBuffer);

从前端接收数据:-

await api
  .get(`${baseURL}/${fetchURL}`, {responseType: "blob"})
  .then((response) => {
    const contentType = response.headers["content-type"];
    const extension = "xlsx";

    const filename = `${fileName}.xlsx`;
    const blob = new Blob([response.data], { type: contentType });

    const url = URL.createObjectURL(blob);

    const link = document.createElement("a");
    link.href = url;
    link.download = filename;
    document.body.appendChild(link);
    link.addEventListener("load", () => {
      document.body.removeChild(link);
    });

    link.click();
  });
© www.soinside.com 2019 - 2024. All rights reserved.