关于javascript:JS-json数据导出为Excel

3次阅读

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

利用 html 里 table 将 json 数据导出为 excel(.xls)

  1. 将 json 数据组装到 table 标签里,能够在 table 及其子标签里进行 css 款式设置。
  2. 将 table 增加到 html 中,在 html 中退出 excel 和 sheet 元素
  3. 将 html 编码为 excel 文件,并进行下载
<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
  });
}

// 表头数据组装,多级表头
let thData = [[{text: '人员信息表', colspan: thead.length}],
  [{text: 'ID', rowspan: 2},
    {text: '根本信息', colspan: thead.length - 1},
  ],
  thead.slice(1, thead.length)
];
exportExcel(thead, tbody, '人员信息表', thData);

exportExcel(thead, tbody, sheetName, thData) {
  /**
   * 将数据组装到 table 里
   * 减少 \t 为了不让表格显示迷信计数法或者其余格局
   */
  let html = '';
  if (thData) { // 多级表头
    thData.map(list => {
      html += '</tr>';
      list.map(item => {html += `<th colspan="${item.colspan ? item.colspan : 1}" rowspan="${item.rowspan ? item.rowspan : 1}">`;
        html += item.text + '\t';
        html += '</th>';
      });
      html += '</tr>';
    });
  } else { // 单级表头
    html += '</tr>';
    thead.map(item => {
      html += `<th>`;
      html += item.text + '\t';
      html += '</th>';
    });
    html += '</tr>';
  }

  tbody.map(item => {
    html += '<tr>';
    thead.map(v => {
      html += '<td style="text-align: center;">';
      html += (item[v.key] ? item[v.key] : '') +'\t';
      html += '</td>';
    });
    html += '</tr>';
  });

  // 将 table 增加到 html 中,在 html 中退出 excel 和 sheet 元素
  let template = '';
  template += '<html lang="" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel">';
  template += '<head><title></title>';
  template += '<xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>';
  template += '<x:Name>';
  template += sheetName;
  template += '</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions>';
  template += '</x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml>';
  template += '</head>';
  template += '<body><table>';
  template += html;
  template += '</table></body>';
  template += '</html>';

  // 将 html 编码为 excel 文件,并下载
  let url = 'data:application/vnd.ms-excel;base64,' + window.btoa(unescape(encodeURIComponent(template)));
  let a = document.createElement('a');
  a.href = url;
  a.download = sheetName;
  a.click();}
</script>

成果如下:

正文完
 0