What could be the reason for JavaScript code successfully exporting to Excel using the old office extension .xls but encountering issues when trying to export

I am currently working on exporting an HTML table to Excel using JavaScript. I have encountered an issue where it does not export to the newer version of Excel with the xlsx extension.

However, it works fine and exports to older versions of Excel with the xls extension.

When attempting to export from the HTML table to Excel with the new xlsx extension, I receive an error message:

cannot open file `.xlsx` because the file extension is not valid or the file is corrupted.

So, how can I solve this problem in order to work with the xlsx extension and open the newer version of Excel?

The function below is used to get selected civil IDs:

function getselected_civilid() {
    debugger
    var selectedCivilIds = [];
    $("input[name='statusCheckbox']:checked").each(function () {
        selectedCivilIds.push($(this).val());
    });

    if (selectedCivilIds.length > 0) {
        // Create an HTML table with headers
        var table = "<table><tr><th>...</th></tr>";

     
        $("input[name='statusCheckbox']:checked").each(function () {
            var row = $(this).closest("tr");
            var cells = row.find("td");

            table += "<tr>";
            cells.each(function () {
                table += "<td>" + $(this).text() + "</td>";
            });
            table += "</tr>";
        });

        table += "</table>";

     
        var blob = new Blob([table], {
            type: "application/vnd.ms-excel;charset=utf-8"
        });
 
        var link = document.createElement("a");
        link.href = URL.createObjectURL(blob);
        link.download = "LastData.xls";
        link.click();
    }
}

When debugging the variable var table, it provides me with the HTML table script as shown in the fiddle linked below. How can I export this to Excel with the xlsx format?

https://jsfiddle.net/36s1qhov

How can I modify the following section to export to Excel as a xlsx sheet:

var blob = new Blob([table], {
            type: "application/vnd.ms-excel;charset=utf-8"
        });
 
        var link = document.createElement("a");
        link.href = URL.createObjectURL(blob);
        link.download = "LastData.xls";
        link.click();

Answer №1

Did you know that the file extension "xlsx" is more than just a simple label? In reality, it represents a format of a zip package that includes XML and various other files. Naming a file as "something.xlsx" won't automatically make it functional - it needs to be properly packaged beforehand.
To handle this packaging process, consider utilizing pre-existing libraries such as https://www.npmjs.com/package/xlsx.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Applying inline styles in PHP using if/else conditions

I want to customize the appearance of my table based on the status of each entry. Specifically, Completed = Green & Pending = Orange This involves PHP code that retrieves data from a MySQL database. $query = mysql_query("SELECT * FROM cashouts WH ...

Tips for setting up electron.js on a linux operating system

Seeking guidance to successfully install electron.js on a Linux operating system. Here are the issues I'm encountering: Installation Command sudo npm i electron Terminal Output /usr/bin/electron -> /usr/lib/node_modules/electron/cli.js <a ...

Is there a way to retrieve a raw value from the API response that matches the one shown in POSTMAN, but my attempts have been unsuccessful?

Looking for some assistance with fetching data from a front-end (React) to the raw value in JSON. Specifically, I'm having trouble with the login functionality. When I input my email and password, the response should match what I see in POSTMAN, but i ...

How to make a HTML div background fill the entire page

Is there a way to extend the background in a div so that it adjusts to fit the screen resolution? I also want to include a navigation bar at the top right corner of this div for the intro page. There will be additional content in other divs positioned be ...

Leverage PHP to dynamically populate a chart.js visualization with information sourced from an SQLite Database

I'm attempting to use chart.js to display data from an SQLite database using PHP, but I've been running into issues. Despite following multiple online tutorials, my graph remains empty or disappears altogether. This is my first time working with ...

Utilizing jQuery to target elements that are dynamically generated upon successful AJAX response

When handling dynamically created elements on ajax success, I encountered an issue. I have multiple checkboxes within a table and when the table content is replaced on ajax success, I am unable to select any new checkbox. While it is possible to trigger cl ...

The function CKEDITOR.replace() is not defined

I'm currently utilizing backbone-forms and I am looking to swap out my textArea with CKEDITOR. However, when I try to implement the code, I keep encountering an error message: Uncaught TypeError: undefined is not a function (for CKEDITOR line) defin ...

Modify a property of an object using the useState Hook, where the property name is dynamically retrieved from a variable

const [fee, setFee] = useState({newPatient:'',establishedPatient:''}) const field1='newPatient' const field2='establishedPatient' To modify the fee object properties, I am looking to dynamically assign ...

Struggling to grasp the concept of Vue3 style binding

While browsing the Vue website, I came across a particular example that left me puzzled. Inside the <script> section, there is this code: const color = ref('green') function toggleColor() { color.value = color.value === 'green' ...

Different floating divisions that are tightly packed adjacent to each other

I'm dealing with dynamically created divs that have variable content, all following the same CSS rules. My goal is to organize them into 2 columns without any space in between. I attempted to use float: left/right, but there still remains space at the ...

Iterate through a jQuery function to retrieve values from checkboxes starting from the 4th one that has been clicked

I am currently using a loop in a form to calculate the total price of a product based on user selections. However, I have encountered a challenging task where certain checkbox groups have specific rules. For instance, group A should only contribute to the ...

The form data is being submitted multiple times by Ajax

Using jQuery and the Dialog widget, I have created a form that opens when the user clicks on a link. The form contains text fields and a file field for uploading files. When the user clicks on "Add File", Ajax uploads the file first and then makes a second ...

What is the reason behind Ember choosing to install everything as devDependencies rather than regular dependencies?

Ember CLI applications have a package.json file that lists everything as dev dependencies, including packages needed in the app's production version such as ember and ember-data. If you would like to see an example, check out this sample: https://git ...

What is the best method to store the name of an image as a session variable?

<!--images acting as buttons--> <form> <img src="peanuts.jpg"" class="qac left" onclick="qac_search()" name="Peanuts"> <img src="milk.jpg" class="qac" onclick=&qu ...

Removing Form Fields Utilizing Javascript

Is it possible to create a unique function in Javascript that automatically removes a form field if it remains unfilled? <form id="myform"> <label for="q1" id="q1label">question 1</label> <input type="text" id="q1" name="q1"/> < ...

How can I make the navbar in Angular stay fixed in place?

After using the ng generate @angular/material:material-nav --name=home command to create a navbar, I am trying to make it fixed at the top while scrolling. I attempted using position: fixed; on my mat-sidenav-content but it didn't work. Does anyone ha ...

Exploring the Connection Issues Between Spring 3, Ajax, and JQuery: Troubleshooting Controller Request Failures

Answer: In my exploration of Spring 3, Ajax and JQuery, I created a small web application named "acme" to understand the connection between these three technologies. During this process, I encountered an issue where the handler method getAddressList() in ...

Navigating through a JSON object in JavaScript by employing regular expressions

Is there a way to extract the "Value" of elements "Data1", "Data2", "Data3", "Data4" from a JSON object without resorting to regex? I've heard that using regex with JSON is not recommended. <script> abc = { "model": { ... } } </script> ...

Using single and double quotes in combination with brackets in PHP: a guide

My struggle lies in using single and double quotes along with brackets in PHP $nestedData[] = '<a href="JavaScript:newPopup('loghistory.php?logid='.$row['user_id'].'')"> History('.$countqry.')</a>&a ...

Running a Python script through a Javascript event

I'm looking to enhance my webpage by implementing a feature where users can generate a personalized QR code with the click of a button. My current setup involves a Python script that creates the QR code image and saves it as a .png file. I want to int ...