Skip to content

Instantly share code, notes, and snippets.

@hero9
Last active April 19, 2022 10:53
Show Gist options
  • Save hero9/06d5a7d2c5fdff0ee3968d71483385ce to your computer and use it in GitHub Desktop.
Save hero9/06d5a7d2c5fdff0ee3968d71483385ce to your computer and use it in GitHub Desktop.
React custom hook, which exports data to excel!
import * as XLSX from 'xlsx';
import FileSaver from 'file-saver';
// Pass tree: true if want to get excel with multiple pages
export const useExportData = (fileName: string, csvData: any, tree?: boolean) => {
let ws: XLSX.WorkSheet;
const fileType =
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';
const fileExtension = '.xlsx';
if (tree) {
const wb = XLSX.utils.book_new();
Object.keys(csvData).forEach((item) => {
if (csvData[item].length) {
const header = Object.keys(csvData[item][0]);
ws = XLSX.utils.json_to_sheet([header], {
skipHeader: true,
});
} else {
ws = {};
}
if (Array.isArray(csvData[item])) {
XLSX.utils.sheet_add_json(ws, csvData[item], {
skipHeader: true,
origin: 1,
});
XLSX.utils.book_append_sheet(wb, ws, item);
}
});
const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
const data = new Blob([excelBuffer], { type: fileType });
return () => FileSaver.saveAs(data, fileName + fileExtension);
}
if (Array.isArray(csvData) && csvData.length) {
const header = Object.keys(csvData[0]);
ws = XLSX.utils.json_to_sheet([header], {
skipHeader: true,
});
XLSX.utils.sheet_add_json(ws, csvData, {
skipHeader: true,
origin: 1,
});
} else {
const data = Object.keys(csvData).reduce((acc, key) => {
let value = csvData[key];
if (Array.isArray(value)) {
value = value.join(';;');
}
if (value && typeof value === 'object') {
value = JSON.stringify(value);
}
acc[key] = value;
return acc;
}, {} as { [key in string]: any });
ws = XLSX.utils.json_to_sheet([data]);
}
const wb = { Sheets: { [fileName]: ws }, SheetNames: [fileName] };
const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
const data = new Blob([excelBuffer], { type: fileType });
return () => FileSaver.saveAs(data, fileName + fileExtension);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment