Use JS to export Table data to Excel (2 methods)

Recently developed projects need to use the function of exporting Excel online, so I found a lot of examples on the Internet, and then I will share two cases of JS online exporting Excel. Since the data displayed by Table is used in the project, I found The case is also exported to Excel according to Table. (Don't talk nonsense, just go to the code!)

Case number one:

Public calling method:

//导出Excel公共方法
var tablesToExcel = (function() {
  var uri = 'data:application/vnd.ms-excel;base64,'
  , tmplWorkbookXML = '<?xml version="1.0"?><?mso-application progid="Excel.Sheet"?><Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">'
  + '<DocumentProperties xmlns="urn:schemas-microsoft-com:office:office"><Author>Axel Richter</Author><Created>{created}</Created></DocumentProperties>'
  + '<Styles>'
  + '<Style ss:ID="Currency"><NumberFormat ss:Format="Currency"></NumberFormat></Style>'
  + '<Style ss:ID="Date"><NumberFormat ss:Format="Medium Date"></NumberFormat></Style>'
  + '</Styles>'
  + '{worksheets}</Workbook>'
  , tmplWorksheetXML = '<Worksheet ss:Name="{nameWS}"><Table>{rows}</Table></Worksheet>'
  , tmplCellXML = '<Cell{attributeStyleID}{attributeFormula}><Data ss:Type="{nameType}">{data}</Data></Cell>'
  , base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s)));}
  , format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) ;};
  return function(tables, wsnames, wbname, appname) {
    var ctx = "";
    var workbookXML = "";
    var worksheetsXML = "";
    var rowsXML = "";

    for (var i = 0; i < tables.length; i++) {
      if (!tables[i].nodeType) tables[i] = document.getElementById(tables[i]);

// 控制要导出的行数
      for (var j = 0; j < tables[i].rows.length; j++) {
        rowsXML += '<Row>';

//  控制导出的列数
        for (var k = 0; k < tables[i].rows[j].cells.length; k++) {
          var dataType = tables[i].rows[j].cells[k].getAttribute("data-type");
          var dataStyle = tables[i].rows[j].cells[k].getAttribute("data-style");
          var dataValue = tables[i].rows[j].cells[k].getAttribute("data-value");
          dataValue = (dataValue)?dataValue:tables[i].rows[j].cells[k].innerHTML;
          var dataFormula = tables[i].rows[j].cells[k].getAttribute("data-formula");
          dataFormula = (dataFormula)?dataFormula:(appname=='Calc' && dataType=='DateTime')?dataValue:null;
          ctx = {  attributeStyleID: (dataStyle=='Currency' || dataStyle=='Date')?' ss:StyleID="'+dataStyle+'"':''
                 , nameType: (dataType=='Number' || dataType=='DateTime' || dataType=='Boolean' || dataType=='Error')?dataType:'String'
                 , data: (dataFormula)?'':dataValue
                 , attributeFormula: (dataFormula)?' ss:Formula="'+dataFormula+'"':''
                };
          rowsXML += format(tmplCellXML, ctx);
        }
        rowsXML += '</Row>';
      }
      ctx = {rows: rowsXML, nameWS: wsnames[i] || 'Sheet' + i};
      worksheetsXML += format(tmplWorksheetXML, ctx);
      rowsXML = "";
    }

    ctx = {created: (new Date()).getTime(), worksheets: worksheetsXML};
    workbookXML = format(tmplWorkbookXML, ctx);

	// 查看后台的打印输出
    //console.log(workbookXML);
    var link = document.createElement("A");
    link.href = uri + base64(workbookXML);
    link.download = wbname || 'Workbook.xls';
    link.target = '_blank';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };
})();

Call: You can write a button case time to trigger him, mine is like this

The first parameter is the id of the Table. If you don’t want to bind one, the
second parameter defaults to this, and you can change it to others. I copied it directly from the Internet without modifying it. The
third parameter is the exported Excel name. You can modify it. The
fourth parameter is the Excel type

//导出Excel按钮
function BtnToExcel_onclick(){
    //第一个参数是Table的id,如果没有要绑定一个
    //第二个参数默认这样,改成其他也可以,我直接复制的网上的,没有修改
    //第三个参数是导出的Excel名称,可以修改你想要的
    //第四个参数是Excel类型
	tablesToExcel(['TableID'], ['ProductDay1'], 'Demo.xls', 'Excel');
}

Summary: I was looking for this at the beginning. The reference can be exported to Excel successfully. After the test, I found that the exported data has data when opened in Excel in Microsoft Office, but there is no data when opened in Excel in WPS. Then I found the reason online, but there is no solution. This has to make me look for other examples from the Internet. Welcome to the great gods to solve the advice!

Case 2:

Public calling method:

var tableToExcel = (function() {
  var uri = 'data:application/vnd.ms-excel;base64,',
      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 http-equiv="Content-Type" content="text/html; 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>{table}</table></body></html>',
      base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) ;},
      format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }); };
  
  return function(table, name, filename) {
    if (!table.nodeType) table = document.getElementById(table);
    console.log(table.innerHTML);
    var ctx = { worksheet: name || 'Worksheet', table: table.innerHTML };//此时的innerHTML数据可以自己自定义 比如json转化 只要值要数据符合即可
    
    var link = document.createElement("A");
    link.href = uri + base64(format(template, ctx));
    link.download = filename;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };
});

Call: You can write a button case time to trigger him, mine is like this

    The first parameter is the id of the Table, if you don’t want to bind a
    second parameter, it’s the default, you don’t need to modify the
    third parameter is the exported Excel name, you can modify it as you want

//导出Excel按钮
function toExcel_onclick(){
    var download = tableToExcel();
    //第一个参数是Table的id,如果没有要绑定一个
    //第二个参数默认这样,不用修改
    //第三个参数是导出的Excel名称,可以修改你想要的
    download("TableID", 'sheet',  "Demo.xls");
}

Summary: Since the first one I found is not compatible with Office and WPS, this pro-test can be used compatible, and everyone is welcome to test the same, and hope to share it with similar and better ones!

The above code source is online, and it is obtained after corresponding modification according to project requirements! It’s a long time to update the blog!

Record, summarize, share! Learning is always on the way!

Guess you like

Origin blog.csdn.net/qq_35340913/article/details/102590714