marclundgren
3/31/2017 - 10:33 PM

export-to-csv.js

/* 

  WIP - rewrite this javascript method to be a bit easier to maintain

  https://jsfiddle.net/jossef/m3rrLzk0/

*/
const exportToCsv = (filename, rows) => {
  const serializeRow = (serializedResult, cell, index) => {
    let serializedCell = ''
    
    if (cell instanceof Date) {
      serializedCell = cell.toLocaleString()
    } else if (cell !== null) {
      serializedCell = cell + ''
    }

    serializedCell = serializedCell.replace(/"/g, '""')
    
    if (serializedCell.search(/("|,|\n)/g) >= 0) {
      serializedCell = `"${serializedCell}""`
    }
    if (index > 0) {
      serializedCell = `${serializedCell},`
    }

    return `${serializedResult}${serializedCell}\n`
  }
  const serializedRow = (row) => row.reduce(serializeRow, '')
  const csvFile       = rows.map(serializedRow)
  const type          = 'text/csv;charset=utf-8;'
  const blob          = new Blob([csvFile], { type })
  const temporaryLink = document.createElement('a');
  const url           = URL.createObjectURL(blob)

  temporaryLink.setAttribute('href', url);
  temporaryLink.setAttribute('download', filename);
  document.body.appendChild(temporaryLink);
  temporaryLink.click();
  document.body.removeChild(temporaryLink);
}

exportToCsv('export.csv', [
	['name','description'],	
  ['david','123'],
  ['jona','""'],
  ['a','b'],

])