Blame view

src/utils/csv.js 1.51 KB
43509ad8   梁灏   Table support exp...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
  // https://github.com/Terminux/react-csv-downloader/blob/master/src/lib/csv.js
  
  const newLine = '\r\n';
  
  export default function csv(columns, datas, separator = ',', noHeader = false) {
      let columnOrder;
      const content = [];
      const column = [];
  
      if (columns) {
          columnOrder = columns.map(v => {
              if (typeof v === 'string') {
                  return v;
              }
              if (!noHeader) {
                  column.push((typeof v.title !== 'undefined') ? v.title : v.key);
              }
              return v.key;
          });
          if (column.length > 0) {
              content.push(column.join(separator));
          }
      } 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);
  
              if (!noHeader) {
                  content.push(columnOrder.join(separator));
              }
          }
      }
  
      if (Array.isArray(datas)) {
          datas.map(v => {
              if (Array.isArray(v)) {
                  return v;
              }
              return columnOrder.map(k => {
                  if (typeof v[k] !== 'undefined') {
                      return v[k];
                  }
                  return '';
              });
          }).forEach(v => {
              content.push(v.join(separator));
          });
      }
      return content.join(newLine);
  }