• Derived form
  • { name, header, data }
  • Name Indicates the name of the table
  • {name[must], key[must], callback[not must]}, callback(item) = {raw, _index}
  • Data Table data, optional

Tool source

// Retrieve table header data
function extractHeader(header) {
  const title = [];
  const key = [];
  const callback = [];
  for (let i = 0; i < header.length; i++) {
    const item = header[i];
    if (item.name) title.push(item.name);
    if (item.key) key.push(item.key);
    if (item.key && item.callback) callback[item.key] = item.callback;
  }
  return { title, key, callback };
}

// A typo
function error(value) {
  console.log(value);
  return false;
}

// Return the table name
function getName(name) {
  if (name) {
    return name + ".csv";
  } else {
    return new Date().toISOString().substring(0.10) + ".csv"; }}// Process data
function handeData(raw, csvHead) {
  const csvData = [];
  for (let i = 0; i < raw.length; i++) {
    const cache = [];
    for (let j = 0; j < csvHead.key.length; j++) {
      const key = csvHead.key[j];
      // If there is a callback function, use the callback function to process data; otherwise, press key
      if (csvHead.callback[key])
        cache.push(csvHead.callback[key]({ raw: raw[i], _index: i }));
      else cache.push(raw[i][key] ?? "");
    }
    csvData.push(cache.join(",") + "\n");
  }
  return csvData;
}

// Download the file
function downFile(csvName, csvData) {
  const csvURL =
    "data:text/csv; charset=utf-8,\ufeff" + encodeURIComponent(csvData.join(""));
  let downloadLink = document.createElement("a");
  downloadLink.href = csvURL;
  downloadLink.download = csvName;
  document.body.appendChild(downloadLink);
  downloadLink.click();
  document.body.removeChild(downloadLink);
}

/* * export table * {name, header, data, index} * name table name, not mandatory * header data, must, {name[must], key[must], callback[not must]} * >>>> callback(item) = {raw, _index} * data table data, Not must * /
const exportCsv = function(params = {}) {
  // The header must be passed in
  if(! params["header"]) return error('[EEROR] : No incoming header! `);
  // Initialize the table data
  const csvData = [];
  // Initialize the table name
  const csvName = getName(params["name"]);
  // Initialize table header data
  const csvHead = extractHeader(params["header"]);
  // Whether the serial number is required
  csvData.push(csvHead.title.join(",") + "\n");
  // Process datacsvData.push(... handeData(params["data"], csvHead));
  // Process files
  downFile(csvName, csvData);
};

export default exportCsv;

Copy the code

Using the example

exportCsv({
  name: "".header: [{
  	name: "Serial number".key: "index".callback: item= > {
  	  returnitem._index; }}].data: []}};Copy the code