有两天,我试图从react的tables组件中导出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"}
]现在我不知道如何在react中使用`优秀的导出,如果你知道更好的库可以帮助我,请提出来,谢谢
发布于 2019-03-16 16:27:46
ExcellentExport用于将常规的超文本标记语言表格转换为CSV或XLS。在我看来,您已经有了原始数据,所以您可以直接直接转换它,完全绕过React或ExcellentExport:
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)
https://stackoverflow.com/questions/55194234
复制相似问题