简体   繁体   English

Node.js, exceljs - 下载的 excel 文件已损坏且内容错误

[英]Node.js, exceljs - Downloaded excel file is corrupted and also has wrong content

With my NodeJS API I want to achieve download of an excel file.使用我的 NodeJS API 我想下载 excel 文件。 I am using exceljs npm package.我正在使用 exceljs npm package。

So the idea is: I want to read the csv file and parse the data, later I want to also read a template excel file and fill this excel file with data from csv. So the idea is: I want to read the csv file and parse the data, later I want to also read a template excel file and fill this excel file with data from csv. On the end I also want to download this new excel file.最后我还想下载这个新的 excel 文件。

In the first function I set the headers and call the function csvParse();在第一个 function 中,我设置了标题并调用 function csvParse(); In the csvParse() function I read the csv file and parse it and when I parse the data I call the function generateFile();在 csvParse() function 我读取 csv 文件并解析它,当我解析数据时我调用 function generateFile(); In the generateFile() function I read the template file and then write it back to a stream with changed content (I do not change the content yet, but will do that when I will actually download the right file).在 generateFile() function 中,我读取了模板文件,然后将其写回 stream 并更改了内容(我还没有更改内容,但是当我实际下载正确的文件时会这样做)。

I don't know what I am doing wrong.我不知道我做错了什么。

export const generateExcel = async (req: Request, res: Response) => {
  try {
    res.setHeader("Content-disposition", "attachment; filename=" + "Report.xlsx");
    res.contentType(
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    );

    await csvParse();       

    return res.status(200).json("Success");
  } catch (err) {
    return res.status(500).json("False");
  }
};

const csvParse = async () => {
  fs.createReadStream("./content/TestCsv.csv")
    .pipe(csv.parse())
    .on("error", (error: any) => console.log("Error"))
    .on("data", (row: any) => {
      let line: any = String(row);
      line = line.split(";");
      //let parsedData = line[0];
      let parsedData = line;
      allParsedData.push(parsedData);
    })
    .on("end", (rowCount: any) => {
      let test = allParsedData.toString();
      generateFile(test);
    });
};

const generateFile = (data: any) => {
  return new Promise<fs.ReadStream>((resolve, reject) => {
    const workbook = new Excel.Workbook();

    workbook.xlsx.readFile("./utilities/template.xlsx").then(() => {
      workbook.xlsx.writeFile("./content/Test.xlsx").then(
        () => {
          let stream = fs.createReadStream("./content/Test.xlsx");
          stream.on("close", () => {
            fs.unlink("./content/Test.xlsx", (error) => {
              if (error) {
                throw error;
              }
            });
          });

          resolve(stream);
        },
        (err) => {
          throw err;
        }
      );
    });
  });
};

So With my code I achieve download of an file, but it is corrupted.因此,使用我的代码,我实现了文件的下载,但它已损坏。 If I change the downloaded file to csv the content of the file is only string "Success".如果我将下载的文件更改为 csv 文件的内容只是字符串“成功”。

Source code: https://github.com/zigax1/mean-generate-download-excel/tree/master源代码: https://github.com/zigax1/mean-generate-download-excel/tree/master

You need to set type of response when you are sending file.您需要在发送文件时设置响应类型。

  return res.type("application/octet-stream").status(200).send(data);

data is of type const file = await book.xlsx.writeBuffer();数据类型为const file = await book.xlsx.writeBuffer(); buffer.缓冲。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM