【问题标题】:Exclude table columns while exporting it into Excel in JavaScript在 JavaScript 中将表列导出到 Excel 时排除表列
【发布时间】:2020-06-13 06:59:05
【问题描述】:

我必须将我的 HTML 表格导出到 Excel 表格中。我研究了很多并找到了解决方案。它对我有用,但问题是,我的表数据中有一些图像字段,我想从表导出中删除它(假设第一列)。如何修改我的代码以获得所需的结果?

downloadVenues = () => {
  var downloadLink;
  var dataType = 'application/vnd.ms-excel';
  var tableSelect = document.getElementById("venue-table");
  var tableHTML = tableSelect.outerHTML.replace(/ /g, '%20');

  // Specify file name
  var filename = 'venues_data.xls';

  // Create download link element
  downloadLink = document.createElement("a");

  document.body.appendChild(downloadLink);

  if (navigator.msSaveOrOpenBlob) {
    var blob = new Blob(['\ufeff', tableHTML], {
      type: dataType
    });
    navigator.msSaveOrOpenBlob(blob, filename);
  } else {
    // Create a link to the file
    downloadLink.href = 'data:' + dataType + ', ' + tableHTML;

    // Setting the file name
    downloadLink.download = filename;

    //triggering the function
    downloadLink.click();
  }
}

【问题讨论】:

  • 我也有这个问题,代码完全相同。你解决了吗?
  • 是的,我整理出来了。我不是从表中导出数据,而是从 API 数据本身导出的。
  • 我已经解决了这个问题,将在这里发布答案。

标签: javascript excel reactjs typescript react-table


【解决方案1】:

这是一种在导出到 Excel 之前删除所有 td、tr、th 或具有类或 id 的任何其他内容的方法。

将 .remove-this 类设置为您要删除的任何 th 和 td。

function exportTableToExcel(tableID, filename = ''){

var table = document.getElementById(tableID);
var cloneTable = table.cloneNode(true);
jQuery(cloneTable).find('.remove-this').remove();

var downloadLink;
var dataType = 'application/vnd.ms-excel';
var tableSelect = cloneTable;
var tableHTML = tableSelect.outerHTML.replace(/ /g, '%20');

// Specify file name
filename = filename?filename+'.xls':'excel_data.xls';

// Create download link element
downloadLink = document.createElement("a");

document.body.appendChild(downloadLink);

if(navigator.msSaveOrOpenBlob){
    var blob = new Blob(['\ufeff', tableHTML], {
        type: dataType
    });
    navigator.msSaveOrOpenBlob( blob, filename);
}else{
    // Create a link to the file
    downloadLink.href = 'data:' + dataType + ', ' + tableHTML;

    // Setting the file name
    downloadLink.download = filename;
    
    //triggering the function
    downloadLink.click();
}

}

原码:https://www.codexworld.com/export-html-table-data-to-excel-using-javascript/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-15
    相关资源
    最近更新 更多