diff --git a/src/components/table/table.vue b/src/components/table/table.vue index e482ca9..0cc801e 100644 --- a/src/components/table/table.vue +++ b/src/components/table/table.vue @@ -714,8 +714,9 @@ let noHeader = false; if ('noHeader' in params) noHeader = params.noHeader; - const data = Csv(columns, datas, ',', noHeader); - ExportCsv.download(params.filename, data); + const data = Csv(columns, datas, params, noHeader); + if (params.callback) params.callback(data); + else ExportCsv.download(params.filename, data); } }, created () { diff --git a/src/utils/csv.js b/src/utils/csv.js index ff03c17..b060541 100644 --- a/src/utils/csv.js +++ b/src/utils/csv.js @@ -1,25 +1,39 @@ -// https://github.com/Terminux/react-csv-downloader/blob/master/src/lib/csv.js +/* + inspired by https://www.npmjs.com/package/react-csv-downloader + now removed from Github +*/ const newLine = '\r\n'; +const appendLine = (content, row, { separator, quoted }) => { + const line = row.map(data => { + if (!quoted) return data; + // quote data + data = typeof data === 'string' ? data.replace(/"/g, '"') : data; + return `"${data}"`; + }); + content.push(line.join(separator)); +}; -export default function csv(columns, datas, separator = ',', noHeader = false) { +const defaults = { + separator: ',', + quoted: false +}; + +export default function csv(columns, datas, options, noHeader = false) { + options = Object.assign({}, defaults, options); let columnOrder; const content = []; const column = []; if (columns) { columnOrder = columns.map(v => { - if (typeof v === 'string') { - return v; - } + if (typeof v === 'string') return v; if (!noHeader) { - column.push((typeof v.title !== 'undefined') ? v.title : v.key); + column.push(typeof v.title !== 'undefined' ? v.title : v.key); } return v.key; }); - if (column.length > 0) { - content.push(column.join(separator)); - } + if (column.length > 0) appendLine(content, column, options); } else { columnOrder = []; datas.forEach(v => { @@ -29,27 +43,17 @@ export default function csv(columns, datas, separator = ',', noHeader = false) { }); if (columnOrder.length > 0) { columnOrder = columnOrder.filter((value, index, self) => self.indexOf(value) === index); - - if (!noHeader) { - content.push(columnOrder.join(separator)); - } + if (!noHeader) appendLine(content, columnOrder, options); } } if (Array.isArray(datas)) { - datas.map(v => { - if (Array.isArray(v)) { - return v; + datas.forEach(row => { + if (!Array.isArray(row)) { + row = columnOrder.map(k => (typeof row[k] !== 'undefined' ? row[k] : '')); } - return columnOrder.map(k => { - if (typeof v[k] !== 'undefined') { - return v[k]; - } - return ''; - }); - }).forEach(v => { - content.push(v.join(separator)); + appendLine(content, row, options); }); } return content.join(newLine); -} \ No newline at end of file +} -- libgit2 0.21.4