网页请求的数据导出
EASY
Code:
in .html
<button (click)="exportCSV()">导出CSV</button>
in .ts
exportCSV() {
let dataObj = {
colname: {
name: "姓名",
city: "城市",
age: "年龄"
},
data: [
{
name: "Wing",
city: "Paglieta",
age: "25"
}, {
name: "Whitney",
city: "Bear",
age: "32"
}, {
name: "Oliver",
city: "Bruderheim",
age: "31"
}
]
};
let dataStr = JSON.stringify(dataObj);
this.electronService.send('export-csv', dataStr);
}
in main
ipcMain.on("export-csv", (event, arg) => {
let options = {
title: "导出CSV",
message: "导出信息",
detail: "导出详情",
buttons: ["保存", "取消"],
filters: [
{name: 'CSV', extensions: ['csv']}
],
defaultId: 0,
cancelId: 1
};
dialog.showSaveDialog(options, response => {
console.log(response);
let dataObj = JSON.parse(arg);
let dataStr = "";
for (let cell in dataObj.colname) {
dataStr = dataStr + '"' + dataObj.colname[cell] + '",'
}
dataStr = dataStr.substring(0, dataStr.length - 1) + "\r\n";
for (let m in dataObj.data) {
for (let n in dataObj.data[m]) {
dataStr = dataStr + '"' + dataObj.data[m][n] + '",'
}
dataStr = dataStr.substring(0, dataStr.length - 1) + "\r\n";
}
fs.writeFile(response, dataStr, 'utf8', function (err) {
if (err) throw err;
console.log("Export Success!");
});
});
});
网友评论