【问题标题】:CSV file has an error or it's not an SYLYK File when adding ID header添加 ID 标头时 CSV 文件有错误或不是 SYLYK 文件
【发布时间】:2020-11-19 18:34:45
【问题描述】:

所以我创建了一个 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 文件时,我真正想解决这个警告。

【问题讨论】:

    标签: javascript excel csv npm wps


    【解决方案1】:

    如果您输入文本文件的第一个字母 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());
    })();

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-10
      • 1970-01-01
      • 2017-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-18
      相关资源
      最近更新 更多