How to export objects to a csv file using pure JavaScript All In One

发布时间 2023-10-17 15:00:55作者: xgqfrms

How to export objects to a CSV file using pure JavaScript All In One

如何使用纯 JavaScript 将对象导出到 CSV 文件

CSV

CSV 使用, / 逗号 分隔

CSV file separator
CSV 文件分隔符

Comma-separated values (CSV)

image

Comma-separated values, a file format and extension

逗号分隔值、文件格式和扩展名

https://en.wikipedia.org/wiki/Comma-separated_values

https://en.wikipedia.org/wiki/CSV

solution

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

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);
}

demos

https://codepen.io/xgqfrms/pen/xxmodaB?editors=1011

![](https://img2023.cnblogs.com/blog/740516/202310/740516-20231017144546167-1303533680.png)

![image](https://user-images.githubusercontent.com/7291672/275735806-77054f7e-edd6-4865-9bd2-226752d0d5fa.png)

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/sEgtw.png

image

enter image description here

(? 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!

refs

https://stackoverflow.com/questions/77306499/javascript-export-object-to-csv-as-a-table



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 ?️,侵权必究⚠️!