json to .csv

从Web以CSV导出数据

引用依赖

npm install file-saver --save
bower install file-saver

https://github.com/eligrey/FileSaver.js/

导出数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
let data={
"0":{"timesheetid":668,"resource":"HenryFan","description":"0","startdate":"2017-10-08T16:00:00.000Z","enddate":"2017-10-14T16:00:00.000Z","state":"Save","activityname":"Developing","projectname":"GAMS Bucket 2"},
"1":{"timesheetid":670,"resource":"HenryFan","description":"","startdate":"2017-10-08T16:00:00.000Z","enddate":"2017-10-14T16:00:00.000Z","state":"Save","activityname":"Developing","projectname":"GAMS Bucket 2"},
"2":{"timesheetid":670,"resource":"HenryFan","description":"","startdate":"2017-10-08T16:00:00.000Z","enddate":"2017-10-14T16:00:00.000Z","state":"Save","activityname":"Developing","projectname":"GAMS Bucket 2"}}
let str = 'TimesheetId,Resource,Description,StartDate,EndDate,State,ActivityName,ProjectName';
for (const i in data) {
str += '\n' + data[i].timesheetid + ',' +
data[i].resource + ',' +
data[i].description + ',' +
data[i].startdate + ',' +
data[i].enddate + ',' +
data[i].state + ',' +
data[i].activityname + ',' +
data[i].projectname
}
//Excel打开后中文乱码添加如下字符串解决
let exportContent = "\uFEFF";
let blob = new Blob([exportContent + "标题,标题,标题\n1,2,3\n4,5,6"], {
type: "text/plain;charset=utf-8"
});
saveAs(blob, "hello world.csv");

读取CSV文件

1
2
3
4
5
6
7
8
9
10
11
12
13
fs.readFile(文件位置, function (err, data) {
if (err) {
console.log(err.stack);
return;
}
data = data.toString();
var table = new Array();
var rows = new Array();
rows = data.split("\r\n");
for (var i = 0; i < rows.length; i++) {
table.push(rows[i].split(","));
}
});