Advertisement
ArCiGo

exportCSV

Mar 9th, 2018
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. public exportTable = (filtered: any) => {
  2.     const { dataSource, filteredRecordCount, totalRecordCount, searchText } = this.state;
  3.     const header = dataSource.columns.map((x: any) => x.Label);
  4.     const visibility = dataSource.columns.map((x: any) => x.Visible);
  5.     let count;
  6.     let search;
  7.     const processRow = (row: any) => {
  8.       if (row instanceof Object) {
  9.         row = Object.keys(row).map((key: any) => row[key]);
  10.       }
  11.  
  12.       let finalVal = '';
  13.  
  14.       for (let i = 0; i < row.length; i++) {
  15.         if (visibility[i]) {
  16.           let innerValue = row[i] === null || row[i] === undefined ? '' : row[i].toString();
  17.           if (moment(row[i], moment.ISO_8601, true).isValid()) {
  18.             innerValue = moment(row[i]).format('MMMM Do YYYY, h:mm:ss a');
  19.           }
  20.  
  21.           let result = innerValue.replace(/"/g, '""');
  22.  
  23.           if (result.search(/("|,|\n)/g) >= 0) {
  24.             result = `"${result}"`;
  25.           }
  26.  
  27.           if (i > 0) {
  28.             finalVal += ',';
  29.           }
  30.  
  31.           finalVal += result;
  32.         }
  33.       }
  34.  
  35.       return `${finalVal}\n`;
  36.     };
  37.  
  38.     let csvFile = '';
  39.     if (header.length > 0) {
  40.       csvFile += processRow(header);
  41.     }
  42.     if (filtered) {
  43.       count = filteredRecordCount;
  44.       search = searchText;
  45.     } else {
  46.       count = totalRecordCount;
  47.       search = '';
  48.     }
  49.  
  50.     dataSource.getAllRecords(count, 0, search)
  51.       .then(({ Payload }: any) => {
  52.         Payload.forEach((row: any) => {
  53.           csvFile += processRow(row);
  54.         });
  55.       }).then(() => {
  56.         const blob = new Blob([`\uFEFF${csvFile}`], {
  57.           type: 'text/csv;charset=utf-8;'
  58.         });
  59.         const fileURL = URL.createObjectURL(blob);
  60.         const downloadLink = document.createElement('a');
  61.         downloadLink.setAttribute('href', fileURL);
  62.         downloadLink.setAttribute('download', 'data.csv');
  63.         downloadLink.click();
  64.         URL.revokeObjectURL(fileURL);
  65.       });
  66.   }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement