关于javascript:JS-json数据导出为Excel单表头不设置样式

42次阅读

共计 899 个字符,预计需要花费 3 分钟才能阅读完成。

<script>
let thead = [{text: 'ID', key: 'id'},
  {text: '姓名', key: 'name'},
  {text: '性别', key: 'sex'},
  {text: '身份证号', key: 'idCard'},
  {text: '出身日期', key: 'birthday'},
  {text: '年龄', key: 'age'},
  {text: '联系电话', key: 'tel'},
];
let tbody = [];
let sexArr = ['男', '女'];
for (let i = 1; i <= 10; i++) {
  tbody.push({
    id: i,
    name: 'xx' + i,
    sex: sexArr[Math.round(Math.random())],
    idCard: '53010020001111234X',
    birthday: '2000/11/11',
    age: 21,
    tel: 13123456789
  });
}
exportExcel(thead, tbody, '人员信息表');

exportExcel(thead, tbody, sheetName) {
  /**
   * 减少 \t 为了不让表格显示迷信计数法或者其余格局
   * 增加 \n 为了表格换行
   */
  let list = [];
  let str = '';
  thead.map((item, i) => {if (i > 0) str += ',';
    str += '\t' + item.text;
  });
  list.push(str);

  tbody.map(item => {
    let str = '';
    thead.map((v, i) => {if (i > 0) str += ',';
      str += '\t' + (item[v.key] ? item[v.key] : '');
    });
    list.push('\n' + str);
  });

  let data = list.join('');
  const url = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(data);
  let a = document.createElement('a');
  a.href = url;
  a.download = sheetName;
  a.click();},
</script>

成果如下:

正文完
 0