How to Export Data to Excel on Button Click Using JavaScript?

Estimated read time 3 min read

To export data to Excel on button click using JavaScript, you can follow these steps:

  1. First, define the data you want to export as a 2D array. Each row in the array represents a row of data in the Excel spreadsheet, and each column represents a cell in that row.
  2. Create a function that converts the 2D array into a CSV (Comma Separated Values) string. A CSV string is a simple text format that can be opened by Excel.
  3. Create a button in your HTML code that will trigger the export when clicked. You can use the <button> element to create the button.
  4. Add an event listener to the button that will call the function that converts the data to a CSV string and download it as an Excel file. To download the file, you can create a link element and simulate a click on it.

Here’s an example code snippet that demonstrates this process:

<!-- Define a button that will trigger the export -->
<button id="export-btn">Export to Excel</button>

<script>
// Define the data to be exported as a 2D array
const data = [
  ['Name', 'Age', 'Gender'],
  ['John', '25', 'Male'],
  ['Jane', '30', 'Female'],
  ['Bob', '40', 'Male']
];

// Function to convert 2D array to CSV string
function convertToCSV(arr) {
  return arr.map(row => row.join(',')).join('\n');
}

// Get a reference to the export button
const exportBtn = document.getElementById('export-btn');

// Add an event listener to the button
exportBtn.addEventListener('click', () => {
  // Convert the data to a CSV string
  const csv = convertToCSV(data);

  // Create a link element and simulate a click on it to download the file
  const link = document.createElement('a');
  link.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv));
  link.setAttribute('download', 'data.csv');
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
});
</script>

In this example, we define a 2D array called data that represents the data we want to export. We then define a function called convertToCSV that converts the 2D array to a CSV string.

Next, we create a button in the HTML code with the ID export-btn that will trigger the export when clicked. We then add an event listener to the button that calls a function when it is clicked.

The function that is called when the button is clicked converts the data array to a CSV string using the convertToCSV function. It then creates a link element and sets its href attribute to the CSV data and its download attribute to the desired filename. The link is then appended to the body of the page, clicked, and then removed from the body. This causes the file to be downloaded with the specified filename.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply