excel - 如何将具有可扩展行的反应表导出到 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,如果你知道更好的库可以帮助我,请提及,谢谢
解决方案
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)
推荐阅读
- android - 如何使用 React Native 开发电子邮件客户端应用程序
- java - android中显示alertdialog时如何不禁用后台交互
- python - Python减少以获取列表中的项目列表
- reactjs - React Router 配置渲染身份验证
- python - “NameError: name 'await' ...”当我尝试将 python 脚本放入 CentOS systemd 服务时
- flutter - 尝试使用谷歌登录包登录谷歌 - Flutter
- mysql - 在mysql数据库中存储服务器日志和前端日志的最佳实践
- java - 获取地图中最后一行的数据
- python - Pyspark:如何添加带有行号的列?
- php - Codeigniter 无法加载请求的文件,仅在托管时