首页 > 解决方案 > 如何将具有可扩展行的反应表导出到 csv 或 excel?

问题描述

有两天我试图从我的表组件中导出 CSV 或 excel,最后我终于找到 ExcelentExport.js,我选择这个是因为它从表而不是数据集导出,如果你想知道为什么我选择这个:我应该说因为我有 120 个表,我需要很长时间来指定表头,从服务器获取的数据格式是这样的

[
  {"id_group":"1","name":"Visitor","members":[],"total":"0","discount":"0"}, 
  {"id_group":"2","name":"Guest","members":[],"total":"0","discount":"0"}
]

现在我不知道我应该如何在反应中使用`Excellent Export,如果你知道更好的库可以帮助我,请提及,谢谢

标签: excelreactjscsvexcellentexport

解决方案


ExcellenceExport用于将常规 HTML 表格转换为 CSV 或 XLS。据我所知,您已经拥有原始数据,因此您可以直接转换它,完全绕过 React 或 ExcellenceExport:

function convertToCSV(tableData, delimiter = ',') {
  if (!Array.isArray(tableData) || !tableData.length) {
    throw new Error('Table data should be a non-empty array of column/value rows');
  }
  
  var colNames = Object.keys(tableData[0]);
  var rows = tableData.map(rowData => {
    var row = [];
    for (var key in rowData) {
      // I noticed that members column is an array, not sure how you handle it
      // but here it joins the members with comma and wraps the whole thing in 
      // double quotes
      if (Array.isArray(rowData[key]) && rowData[key].length) {
        row.push('"' + rowData[key].join(',') + '"');
      } else {
        row.push(rowData[key]);
      }
    }
    return row.join(delimiter);
  });
  rows.unshift(colNames.join(delimiter));
  return rows.join("\n")
}

const csv = convertToCSV([
  {"id_group":"1","name":"Visitor","members":[],"total":"0","discount":"0"}, 
  {"id_group":"2","name":"Guest","members":[],"total":"0","discount":"0"}
])

console.info(csv)


推荐阅读