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

Ensuring the accuracy of user input

Can someone assist me with comparing two dates in JSP? I need validation that alerts the user when a future date is entered. The start date or end date should not be in the future. The date format is 12-5-2011 10:51:49. Any help would be greatly apprecia ...

Is there a way to ensure that the text stays positioned behind the initial image even as the window size is adjusted

<html> <head> <title> Example </title> <style> img:hover {opacity : 0.3;} img {z-index : 1; height : 33%; width : 33%; } .first { position : absolute; top: 0%; left: 0%;} .second {position : absolute; top: 0%; left: 33%; ...

Leverage the power of DOMXPath in combination with the query function

Here is a snippet of HTML code to work with: <ul id="tree"> <li> <a href="">first</a> <ul> <li><a href="">subfirst</a></li> <li><a href=""> ...

What strategies can I implement to streamline, refine, and enhance the efficiency of this jQuery code?

I've been working on the front-end of a website and I have a bunch of jQuery functions. While I'm not a jQuery expert, I have started reading the sitepoint book to improve my skills. I believe that my code could use some cleaning up to make it mo ...

Can a single volume control be used to manage the audio of multiple sources at once?

I am currently working on a project for my personal interactive video website. I am trying to figure out how to create one volume control that can adjust the audio for multiple tracks at once. Can anyone help me with this? So far, I have successfully crea ...

How can I create two buttons on one line in a Struts2 form?

My form has two buttons - one for registering and the other for canceling the form. I created them using the following code: <s:submit name="cancel" key="project.button.cancel" /> <s:submit name="login" key="form.register.registerBtn" /> How ...

Transforming JSON into array format with key-value pairs using JavaScript

Currently, I am working on a web application that is receiving data in a specific format from a node server: "{""elements":[{"10sr2b2":{"total":0,"bad":22,"clients":["fc8e7f","fc8e7e"],"zone":"101900"}}]}" The issue lies in the fact that this data is str ...

Guide on dynamically displaying a page based on the response from express/mssql middleware

I have developed a full stack application that includes a registration feature which successfully adds data to the database. Now, I am looking for a way to conditionally display the home page based on whether the login credentials are correct. Within my l ...

Leveraging NextJS to perform server side rendering by injecting parameters from a caller component

I'm currently in the process of creating an application with a storefront using nextJS. I've successfully utilized getServerSideProps when loading a new page. This particular page is quite complex, as it consists of multiple components, each req ...

Using jQuery, the image name will be displayed once it is selected

When I click on the image and then on the Add button, the image name should be displayed in an alert message. However, it is not working as expected. Below is the code that I have tried so far. If I click on the Chocolate image, the alert message should di ...

Mastering the art of combining images and text harmoniously

I am having trouble aligning my lion image and h1 tag side by side. There seems to be an issue but I can't figure out what it is. h2 { width:50%; float:right; padding:30px 0px 0px 0px; margin:0 auto; } .lion { width:10%; float: left; paddin ...

Retrieve information from the existing URL and utilize it as a parameter in an ajax request

Currently, I am working on a website with only one HTML page. The main functionality involves fetching the URL to extract an ID and then sending it to an API using an AJAX call. Upon success, the data related to the extracted ID is displayed on the page. H ...

The function has exceeded the time limit of 60000 milliseconds. Please make sure that the callback is completed

Exploring the capabilities of Cucumber with Protractor has been an intriguing journey for me. As I delved into creating a feature in Gherkin language, outlining the steps and scenarios necessary for my end-to-end tests, a new world of possibilities opened ...

Steps for setting up an info window on a Google map with multiple markers

I'm having trouble getting the infowindow to pop up on the multiple custom markers I added using AJAX on Google Maps. Everything was working fine before I tried implementing the infowindow and adding the listenMarker() function. The icons were in the ...

What is the right rendering strategy to use for shouldComponentUpdate in React?

Provide an exhaustive list of all props required for rendering shouldComponentUpdate(nextProps, nextState) { if (this.props.color !== nextProps.color) { return true; } if (this.state.count !== nextState.count) { return true; ...

Using Mongoose schema with a reference to an undefined 'ObjectID' data type

I am currently working on establishing relationships between my schemas, and I have encountered some issues with my solution. Here is how my device schema looks like: var deviceSchema = schema({ name : String, type : String, room: {type: mongo ...

Display values in real-time when the text box is modified

Is there a way to update the total value in a text box based on user input using JavaScript and PHP, or just JavaScript? For example, if item "A" costs $25 and the customer orders 5 of "A", the total should automatically display as $125 when the quantity ...

Develop a new object using NodeJS within a module for a function

I am working with a file named item.js exports.itemParam = function(name, price, url, id){ this.name = name; this.price = price; this.id = id; this.url = url; }; In my www.js file, I have imported item.js like this: var item = require('../m ...

@media doesn't seem to be functioning properly when the screen width is below

I've been working on making my website fully responsive, but I've run into an issue where it won't recognize anything below 980px in width. Here is the CSS code I'm using: @media screen and (max-width:1029px){ h1{ font-size ...

Styling Challenge: Making the button inside a form match the design of the button outside the form

I have noticed that the button inside a form has a lot more padding around it compared to the one outside of the form. I am trying to adjust the within-form button so that it matches the padding of the without-form button. HTML/PHP <?php if (! ...