JavaScript将对象作为表导出到csv

ttp71kqs  于 11个月前  发布在  Java
关注(0)|答案(1)|浏览(119)

我有一个JS对象(名为df),它包含许多数组,如下所示:

0: Array(2)
  0: "1405"
  1: "text string 1 #something"
1: Array(2)
  0: "1366"
  1: "text string 2 #hashtag"
603: Array(2)
  0: "92"
  1: "text string 603"

字符串
我想将其导出到csv文件中,如下所示:
| 查看|标题|
| --|--|
| 1405 |文本字符串1 #something|
| 1366 |文本字符串2 #hashtag|
| 92 |文本串603|
我可以使用以下内容导出为csv:

const blob = new Blob([df], { type: "text/csv; charset=utf-8;" });
const url = URL.createObjectURL(blob);

const link = document.createElement("a");
link.setAttribute("href", url);
link.setAttribute("download", "export.csv");

document.body.appendChild(link);
link.click();
document.body.removeChild(link);


但是输出结果很混乱:
| 一|B| C|
| --|--|--|
| 1405 |文本字符串1||
| #某事|||
| | 文本字符串2 #hasthag| text string 2 #hasthag |
我该如何在JS中清理此问题?
编辑:我已经找到了问题的原因是文本字段中的换行符导致剩余文本被推到新的一行。
解决方案是使用regex删除提取文本时的换行符:

innerText.replace(/(\r\n|\n|\r)/gm, " ")

eagi6jfj

eagi6jfj1#

只需将对象转换为CSV字符串即可

const autoDonwload = (obj) => {
  let result = `Views, Title`;
  for(const key in obj) {
    const [num, str] = obj[key];
    result += `\n`;
    result += `${num}, ${str}`;
  }
  // console.log(`result =\n`, result);
  const blob = new Blob([result], { type: "text/csv; charset=utf-8;" });
  const url = URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.setAttribute("href", url);
  link.setAttribute("download", "export.csv");
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};

const obj = {
  0: ["1405", "text string 1 #something"],
  1: ["1366",  "text string 2 #hashtag"],
  603: ["92", "text string 603"],
};

autoDonwload(obj);

字符串

demo


的数据
现场演示
https://codepen.io/xgqfrms/pen/xxmodaB

更新

修复字符串包含,符号问题

const autoDonwload = (obj) => {
  // use `;` instead of `,` ✅
  let result = `Views; Title`;
  for(const key in obj) {
    const [num, str] = obj[key];
    result += `\n`;
    result += `${num}; ${str}`;
  }
  const blob = new Blob([result], { type: "text/csv; charset=utf-8;" });
  const url = URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.setAttribute("href", url);
  link.setAttribute("download", "export.csv");
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};

const obj = {
  // string contains `,` symbol ❓
  0: ["1405", "text, string 1, #something"],
  1: ["1366",  "text string 2 #hashtag"],
  603: ["92", "text string 603"],
};

autoDonwload(obj);



参考文献
https://en.wikipedia.org/wiki/Comma-separated_values

相关问题