Skip to content
Snippets Groups Projects

added excel download button to the pages

2 unresolved threads
Files
11
import React from 'react';
import * as XLSX from "xlsx";
import {ExportType} from "../helpers/constants";
interface DownloadCSVProps {
interface DownloadProps {
data: any[];
filename?: string;
filename: string;
exportType: ExportType;
}
@@ -36,12 +40,48 @@ function convertToCSV(jsonData: any[]): string {
return [header.join(','), ...rows].join('\r\n');
}
function convertToExcel(jsonData: any[], sheetName = "Sheet1"): Blob {
const ws = XLSX.utils.json_to_sheet(jsonData);
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, sheetName);
const wbout = XLSX.write(wb, {bookType: 'xlsx', type: 'binary'});
const buffer = new ArrayBuffer(wbout.length);
const view = new Uint8Array(buffer);
for (let i = 0; i < wbout.length; i++) {
// Convert each character of the binary workbook string to an 8-bit integer and store in the Uint8Array 'view' for blob creation.
view[i] = wbout.charCodeAt(i) & 0xFF;
}
return new Blob([buffer], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8'});
}
const DownloadDataButton: React.FC<DownloadProps> = ({data, filename, exportType}) => {
const downloadData = () => {
let convertedData;
let fileType;
let contentType ;
switch (exportType) {
case ExportType.EXCEL: {
convertedData = convertToExcel(data);
fileType = 'xlsx';
contentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';
Please register or sign in to reply
break;
}
case ExportType.CSV:
default: {
convertedData = convertToCSV(data);
fileType = 'csv';
contentType = 'text/csv;charset=UTF-8';
break;
}
}
const DownloadCSVButton: React.FC<DownloadCSVProps> = ({ data, filename = 'data.csv' }) => {
const blob = new Blob([convertedData], {type: contentType});
filename = filename.endsWith(fileType) ? filename : `${filename}.${fileType}`;
const downloadCSV = () => {
const csv = convertToCSV(data);
const blob = new Blob([csv], { type: 'text/csv' });
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = filename;
@@ -52,9 +92,9 @@ const DownloadCSVButton: React.FC<DownloadCSVProps> = ({ data, filename = 'data.
return (
<>
<button onClick={downloadCSV}>Download CSV</button>
<button onClick={downloadData}>Download {exportType}</button>
</>
);
}
export default DownloadCSVButton;
export default DownloadDataButton;
Loading