vue2 使用x2js json转换成xml
安装:
在项目终端运行以下命令
cnpm install x2js --save
引用:
// 引入模块 import x2js from 'x2js'
全部代码:
<template>
<el-button type="primary" @click="exportExcel">导出</el-button>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue'
import { ElMessage } from 'element-plus'
export default defineComponent({
data() {
return {
testdata: [
{
"noticeId":345646,
"satName":"ZOHREH-2",
"country":"IRN",
"freqMin":456.0,
"freqMax":456.0,
"beamInfoList":
[
{
"beamName":"RS49",
"freqMin":3456.0,
"freqMax":654.0,
"groupInfoList":
[
{
"groupId":567.34,
"freqMin":768.0,
"freqMax":678.0,
"pwrMax":1.0
},
{
"groupId":10600362,
"freqMin":11450.0,
"freqMax":11700.0,
"pwrMax":2.0
},
{
"groupId":10600363,
"freqMin":14000.0,
"freqMax":14500.0,
"pwrMax":3.0
}
]
},
]
}]
}
},
methods: {
exportExcel() {
let x2js = new X2js();
let groupdata = { doc: this.testdata };
//groupdata必须只有一个跟节点noticeData不然导出xml时会报错
// let obj = {
// doc: groupdata,
// };
// 调用x2js 将我们的json数据转换成xml数据格式
console.log(x2js);
let xml = x2js.js2xml(groupdata);
xml = `<?xml version="1.0" ?>` + xml;
console.log(xml);
// 下面就是我们想要的xml文件的数据格式了
// 这里会生成一个url
let url = window.URL.createObjectURL(
new Blob([xml], { type: "text/xml;charset=utf-8" })
);
// 然后就可以创建a标签 最后下载下来了
let link = document.createElement("a");
// 不显示链接
link.style.display = "none";
link.href = url;
// 设置链接属性
link.setAttribute("download", "导出");
//点击链接
document.body.appendChild(link);
link.click();
// 删除连接
document.body.removeChild(link);
},
})

浙公网安备 33010602011771号