A simple way to export front-end tabular data to Excel

method one

/**
 * 导出表格数据到 Excel 文件
 * @param {Array} tableData - 表格数据
 * @param {Array} fieldLabels - 表头组成的数组
 * @param {Array} fieldKeys - 列属性名组成的数组
 * @param {String} fileName - 导出的文件名
 */
function exportExcel(tableData, fieldLabels, fieldKeys, fileName) {
    
    
  let dataStr = fieldLabels.toString() + '\r\n';
  tableData.forEach(item => {
    
    
      fieldKeys.forEach(key => {
    
    
          // 加引号是为了使换行符在单元格内正常显示 
          dataStr += `"${
      
      item[key]}"\t,`;
      });
      dataStr += '\r\n';
  });
  
  // encodeURIComponent 解决中文乱码
  const url = "data:text/xls;charset=utf-8,\ufeff" + encodeURIComponent(dataStr);
  const link = document.createElement("a");
  link.href = url;
  link.download = fileName + ".xls";
  link.style.display = 'none';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link); //释放标签
}

problems encountered

  • In order to prevent the data in the cell from being formatted (for example, too large numbers will be converted to scientific and technical methods), extra characters need to be added after the data, as in the above code \t.

example

const tableData = [
          {
    
     date: '2016-05-02', name: '王小虎', address: '上海市普陀区金沙江路 1518 弄' },
          {
    
     date: '2016-05-04', name: '张小星', address: '上海市普陀区金沙江路 1517 弄' },
          {
    
     date: '2016-05-01', name: '刘小备', address: '上海市普陀区金沙江路 1519 弄' },
          {
    
     date: '2016-05-03', name: '赵小云', address: '上海市普陀区金沙江路 1516 弄' }
      ],
      fieldKeys = ['date', 'name', 'address'],
      fieldLabels = ['日期', '姓名', '地址'],
      fileName = '测试文件';
      
exportExcel(tableData, fieldLabels, fieldKeys, fileName);

Method Two

Export EXCEL via HTML

function exportExcel(tableData, fieldKeys, fieldLabels, fileName){
    
    
    // 用于替换数据中的换行符,是其可以在单元格内正常显示
    const wrapMark = '<br style="mso-data-placement:same-cell;"/>';
    
    // 设置单元格数据显示为文本格式,避免过大的数字以科学计数法的形式显示
    const tdTagHeader = `<td style="mso-number-format:'\@'">`;
    
    let dataStr = '<tr>'

    fieldLabels.forEach(label => {
    
    
      dataStr += `${
      
      tdTagHeader + label}</td>`;
    })

    dataStr += '</tr>';
    tableData.forEach(item => {
    
    
        dataStr += '<tr>'
        fieldKeys.forEach(key => {
    
    
            // 这种方式本质是导出 html 文件,html 中连续的空格符会被合并成一个显示
            // replace(/ /g, '&nbsp;') 将空格符替换成 &nbsp; 使其可以正常显示
            dataStr += tdTagHeader + `${
      
      item[key]}`.replace(/ /g, '&nbsp;').replace(/\n/g, wrapMark) + '</td>';
        });
        dataStr += '</tr>'
    })

    //设置 Worksheet 名
    const workSheet = 'Sheet1'
    
    const template = `<html xmlns:o="urn:schemas-microsoft-com:office:office"
    xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40">
    <head><meta charset="UTF-8" />
    <!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>
    <x:Name>${
      
      workSheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/>
    </x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->
    </head><body><table>${
      
      dataStr}</table></body></html>`;

    const url = 'data:application/vnd.ms-excel;base64,' + window.btoa(unescape(encodeURIComponent(template))) ;
    const link = document.createElement("a");
    
    link.href = url;
    link.download = fileName + ".xls";
    link.style.display = 'none';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

PS: Since the export is essentially an HTML file, <td> 、<tr>the inline style set for the tag will also be correctly applied in Excel.

problems encountered

  • When the exported file is opened with Office, it will prompt that the file format does not match the extension, but it does not affect the normal opening of the file.

Guess you like

Origin blog.csdn.net/dark_cy/article/details/122114517