Ghazaleh Javaheri
Ghazaleh Javaheri

Reputation: 2117

how to export react table with expandable rows to csv or excel?

there is two days that i`m trying to export CSV or excel from my tables component in react and at the end i finally find ExcelentExport.js ,i choose this because it export from table not data-set,and if you want to know why i choose this :i should say because i have 120 tables,and it take me to long to specify table header, format of data that get from server is like this

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

now i don't know how should i use `Excellent Export in react,also if you know better library that can help me please mention it ,thank you

Upvotes: 2

Views: 5425

Answers (1)

jayarjo
jayarjo

Reputation: 16726

ExcellentExport is for converting regular HTML tables to CSV or XLS. From what I see you already have the raw data, so you can simply convert it directly, bypassing React or ExcellentExport altogether:

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)

Upvotes: 3

Related Questions