function convertToCSV(data) {
let csvContent = ""
// 处理数据行
data.forEach(function (row) {
let rowArray = []
Object.values(row).forEach(function (value) {
rowArray.push(`${value}`) // 如果数据中有逗号,建议加引号
})
csvContent += rowArray.join(',') + '\n'
})
// 创建一个 Blob 对象用于创建下载链接
let blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" })
// 创建一个下载链接
let link = document.createElement("a")
if (link.download !== undefined) {
let url = URL.createObjectURL(blob)
link.setAttribute("href", url)
link.setAttribute("download", "data.csv")
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
}
}
// 示例数据
let testData1 = [
{
"id": 1,
"code": "1",
"name": "DC-HYJQ41-F ±400kV 1*1600+4*24B1",
"cableCoreType": 1,
"armoured": 1,
"section": 1600,
"outdia": 47.6,
"shieldDeep": 2.6,
"insulatedDeep": 26,
"insulatedShieldDeep": 1.5,
"innerDeep": 1.5,
"armouredDeep": 5,
"jacketDeep": 4,
"voltage": 231,
"airDeep": 0,
"lossFactor": 0,
"tweentyR": 0.0113
},
{
"id": 2,
"code": "2",
"name": "ZA-DC-YJQ03 ±400kV 1*1600",
"cableCoreType": 1,
"armoured": 4,
"section": 1600,
"outdia": 47.6,
"shieldDeep": 2.6,
"insulatedDeep": 26,
"insulatedShieldDeep": 1.5,
"innerDeep": 1.3,
"armouredDeep": 4.1,
"jacketDeep": 5,
"voltage": 231,
"airDeep": 0,
"lossFactor": 0,
"tweentyR": 0.0113
},
{
"id": 3,
"code": "3",
"name": "HYJQF41-F 127/220 3*500+2*36B1",
"cableCoreType": 2,
"armoured": 1,
"section": 500,
"outdia": 26.5,
"shieldDeep": 2.5,
"insulatedDeep": 27,
"insulatedShieldDeep": 1.2,
"innerDeep": 2,
"armouredDeep": 6,
"jacketDeep": 4,
"voltage": 127,
"airDeep": 0,
"lossFactor": 0.0005,
"tweentyR": 0.0383
},
{
"id": 4,
"code": "4",
"name": "HYJQF41-F 127/220kV 1×500",
"cableCoreType": 1,
"armoured": 1,
"section": 500,
"outdia": 26.4,
"shieldDeep": 2,
"insulatedDeep": 27,
"insulatedShieldDeep": 1.2,
"innerDeep": 1.5,
"armouredDeep": 6,
"jacketDeep": 3.3,
"voltage": 127,
"airDeep": 0,
"lossFactor": 0.0005,
"tweentyR": 0.04
}
]
let showKeys = [
"id",
"code",
"name",
"cableCoreType",
"armoured",
"section",
"outdia",
"shieldDeep",
"insulatedDeep",
"insulatedShieldDeep",
"innerDeep",
"armouredDeep",
"jacketDeep",
"voltage",
"airDeep",
"lossFactor",
"tweentyR"
]
let transData = testData1.map(val => {
return showKeys.map(key => val[key])
})
convertToCSV(transData);
JSON数据转csv文件下载
最新推荐文章于 2024-11-01 18:36:00 发布