Blame view

src/utils/csv.js 1.71 KB
fb847998   Sergio Crisostomo   Improve export to...
1
2
3
4
  /*
    inspired by https://www.npmjs.com/package/react-csv-downloader
    now removed from Github
  */
43509ad8   梁灏   Table support exp...
5
6
  
  const newLine = '\r\n';
fb847998   Sergio Crisostomo   Improve export to...
7
8
9
10
11
12
13
14
15
  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));
  };
43509ad8   梁灏   Table support exp...
16
  
fb847998   Sergio Crisostomo   Improve export to...
17
18
19
20
21
22
23
  const defaults = {
      separator: ',',
      quoted: false
  };
  
  export default function csv(columns, datas, options, noHeader = false) {
      options = Object.assign({}, defaults, options);
43509ad8   梁灏   Table support exp...
24
25
26
27
28
29
      let columnOrder;
      const content = [];
      const column = [];
  
      if (columns) {
          columnOrder = columns.map(v => {
fb847998   Sergio Crisostomo   Improve export to...
30
              if (typeof v === 'string') return v;
43509ad8   梁灏   Table support exp...
31
              if (!noHeader) {
fb847998   Sergio Crisostomo   Improve export to...
32
                  column.push(typeof v.title !== 'undefined' ? v.title : v.key);
43509ad8   梁灏   Table support exp...
33
34
35
              }
              return v.key;
          });
fb847998   Sergio Crisostomo   Improve export to...
36
          if (column.length > 0) appendLine(content, column, options);
43509ad8   梁灏   Table support exp...
37
38
39
40
41
42
43
44
45
      } else {
          columnOrder = [];
          datas.forEach(v => {
              if (!Array.isArray(v)) {
                  columnOrder = columnOrder.concat(Object.keys(v));
              }
          });
          if (columnOrder.length > 0) {
              columnOrder = columnOrder.filter((value, index, self) => self.indexOf(value) === index);
fb847998   Sergio Crisostomo   Improve export to...
46
              if (!noHeader) appendLine(content, columnOrder, options);
43509ad8   梁灏   Table support exp...
47
48
49
50
          }
      }
  
      if (Array.isArray(datas)) {
fb847998   Sergio Crisostomo   Improve export to...
51
52
53
          datas.forEach(row => {
              if (!Array.isArray(row)) {
                  row = columnOrder.map(k => (typeof row[k] !== 'undefined' ? row[k] : ''));
43509ad8   梁灏   Table support exp...
54
              }
fb847998   Sergio Crisostomo   Improve export to...
55
              appendLine(content, row, options);
43509ad8   梁灏   Table support exp...
56
57
58
          });
      }
      return content.join(newLine);
fb847998   Sergio Crisostomo   Improve export to...
59
  }