Skip to content

Instantly share code, notes, and snippets.

@crstnmac
Last active August 5, 2023 15:28
Show Gist options
  • Save crstnmac/da19726e91ebfce35d8b82455773ed5e to your computer and use it in GitHub Desktop.
Save crstnmac/da19726e91ebfce35d8b82455773ed5e to your computer and use it in GitHub Desktop.
Convert data to excel format
import React, { useState } from "react";
export default function useReactHTMLTableToExcel() {
const [isLoading, setIsLoading] = useState(false);
function base64(s) {
return window.btoa(unescape(encodeURIComponent(s)));
}
function format(s, c) {
return s.replace(/{(\w+)}/g, (m, p) => c[p]);
}
function createTableHTML(data, header) {
let tableHTML = '<table><thead><tr>';
// Add header row
if (header && Array.isArray(header)) {
for (const cell of header) {
tableHTML += `<th>${cell}</th>`;
}
tableHTML += '</tr></thead>';
}
tableHTML += '<tbody>';
// Add data rows
for (const row of data) {
tableHTML += '<tr>';
for (const cell in row) {
tableHTML += `<td>${row[cell]}</td>`;
}
tableHTML += '</tr>';
}
tableHTML += '</tbody></table>';
return tableHTML;
}
/* The `downloadExcel` function is responsible for generating and downloading an Excel file based on
the provided data, header, filename, and sheet parameters.
eg: downloadExcel(
data, ["Name", "Age", "Address"], "MyFile", "Sheet 1"
)
*/
async function downloadExcel(data, header, filename, sheet) {
if (!Array.isArray(data)) {
if (process.env.NODE_ENV !== 'production') {
console.error('Data is not a valid array.');
}
return null;
}
setIsLoading(true);
const tableHTML = createTableHTML(data, header);
const sheetName = String(sheet);
const fileExtension = '.xlsx';
const filenameWithExtension = `${String(filename)}${fileExtension}`;
const context = {
worksheet: sheetName || 'Worksheet',
table: tableHTML,
};
const uri = 'data:application/vnd.ms-excel;base64,';
const template =
'<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-mic' +
'rosoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><meta cha' +
'rset="UTF-8"><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:Exce' +
'lWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/>' +
'</x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></' +
'xml><![endif]--></head><body>{table}</body></html>';
const element = window.document.createElement('a');
element.href =
uri +
base64(
format(template, context),
);
element.download = filenameWithExtension;
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
setIsLoading(false);
}
return { downloadExcel, isLoading };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment