Created
September 28, 2023 15:20
-
-
Save rafapolo/6d425da9b8cf0d34426533a43ea85bb8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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