0

所以我创建了一个 node.js 脚本来将数组的对象转换为 CSV 格式,然后我使用了 NPM 库中的 objects-to-csv。首先,想要通过添加 ID 来迭代数组。该脚本已成功创建 CSV 文件。但是当我将它打开到 WPS 和 Microsoft Office 时,会出现一个警告,指出文件有错误或者不是 SYLYK 文件。请看下面的代码。

const ObjectsToCsv = require("objects-to-csv");

// Sample data - two columns, three rows:
const data = [
  { code: "CA", name: "California" },
  { code: "TX", name: "Texas" },
  { code: "NY", name: "New York" },
];

// If you use "await", code must be inside an asynchronous function:
(async () => {
  const iterateWithID = data.map((x, i) => {
    return {
      ID: i + 1,
      code: x.code,
      name: x.name,
    };
  });

  const csv = new ObjectsToCsv(iterateWithID);

  // Save to file:
  await csv.toDisk("./output.csv");

  // Return the CSV file as string:
  console.log(await csv.toString());
})();

这是我将警告打开到 WPS 时的屏幕截图 在此处输入图像描述

我尝试删除数组的迭代,打开CSV文件时没有遇到任何问题。当我打开 CSV 文件时,我真正想解决这个警告。

4

1 回答 1

0

如果您ID输入文本文件的第一个字母,Excel 会错误地假定您正在尝试打开 SYLK 文件。我将您的代码更新为拥有Id而不是ID.

const ObjectsToCsv = require("objects-to-csv");

// Sample data - two columns, three rows:
const data = [
  { code: "CA", name: "California" },
  { code: "TX", name: "Texas" },
  { code: "NY", name: "New York" },
];

// If you use "await", code must be inside an asynchronous function:
(async () => {
  const iterateWithID = data.map((x, i) => {
    return {
      Id: i + 1,
      code: x.code,
      name: x.name,
    };
  });

  const csv = new ObjectsToCsv(iterateWithID);

  // Save to file:
  await csv.toDisk("./output.csv");

  // Return the CSV file as string:
  console.log(await csv.toString());
})();

于 2021-02-25T15:55:11.073 回答