Skip to content

Instantly share code, notes, and snippets.

@rafapolo
Created September 28, 2023 15:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rafapolo/6d425da9b8cf0d34426533a43ea85bb8 to your computer and use it in GitHub Desktop.
Save rafapolo/6d425da9b8cf0d34426533a43ea85bb8 to your computer and use it in GitHub Desktop.
import * as XLSX from 'xlsx';
function generateExcelTemplate() {
// Create a new workbook
const workbook = XLSX.utils.book_new();
// Define your data
const data = [
['Name', 'Email', 'Age'],
['John Doe', 'john@example.com', 30],
['Jane Smith', 'jane@example.com', 25],
];
// Create a new worksheet and add data
const worksheet = XLSX.utils.aoa_to_sheet(data);
// Add the worksheet to the workbook
XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet 1');
// Generate a Blob object containing the Excel file
const blob = XLSX.write(workbook, { bookType: 'xlsx', type: 'blob' });
// Create a download link
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'template.xlsx';
a.textContent = 'Download Excel Template';
// Append the link to the DOM and trigger a click event to download the file
document.body.appendChild(a);
a.click();
// Clean up
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
}
document.getElementById('generateExcel').addEventListener('click', generateExcelTemplate);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment