Exporting an HTML table to Excel while excluding any hidden <td> elements

I have a web application with an HTML table that displays data to users.

I wanted to export the table to Excel and found a jQuery code for it.

However, the exported data includes information that is hidden in the table.

Is there a way to export the table without including the

 <td style="display:none;"> @Html.DisplayFor(modelItem => item.Id) </td>
?

Below is the table structure:

 <table id="tblParts" class="table table-striped">
   <thead>
     <tr>
       <th> Part Number </th>
       <th> Description </th>
       <th> Model </th>
       <th> Order Qty </th>
       <th></th>
     </tr>
   </thead>
   <tbody> @foreach (var item in Model.OrderBy(i => i.PartNumber)) { <tr>
       <td style="display:none;"> @Html.DisplayFor(modelItem => item.Id) </td>
       <td> @Html.DisplayFor(modelItem => item.PartNumber) </td>
       <td> @Html.DisplayFor(modelItem => item.Description) </td>
       <td> @Html.DisplayFor(modelItem => item.Model) </td>
       <td> @Html.DisplayFor(modelItem => item.OrderQty) </td>
     </tr> } </tbody>
 </table>

Here is the Jquery function:

function ExportToExcel(type, fn, dl) {
  var elt = document.getElementById('tblParts');
  var wb = XLSX.utils.table_to_book(elt, {
    sheet: "sheet1"
  });
  return dl ?
    XLSX.write(wb, {
      bookType: type,
      bookSST: true,
      type: 'base64'
    }) :
    XLSX.writeFile(wb, fn || ('Order.' + (type || 'xlsx')));
}

Answer №1

Perhaps it would be beneficial to remove the hidden column before exporting within the export function by assigning a class name to the hidden column. I have included a fiddle for your convenience:

example

HTML

<table id="tblParts" class="table table-striped">
    <thead>
        <tr>
            <th>Part Number </th>
            <th>Description </th>
            <th>Model </th>
            <th>Order Qty </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td style="display: none;" class="item-id">1 </td>
            <td>2</td>
            <td>3 </td>
            <td>4 </td>
            <td>5 </td>
        </tr>
        <tr>
            <td style="display: none;" class="item-id">2 </td>
            <td>2</td>
            <td>3 </td>
            <td>4 </td>
            <td>5 </td>
        </tr>
    </tbody>
</table>

JS

    function ExportToExcel(type, fn, dl) {
            var elt = document.getElementById('tblParts');
            const elements = elt.getElementsByClassName("item-id"); //get column with the class name item-id
            while (elements.length > 0) elements[0].remove(); //if element exist, remove the column

            var wb = XLSX.utils.table_to_book(elt, {
                sheet: "sheet1"
            });
            return dl ?
                XLSX.write(wb, {
                    bookType: type,
                    bookSST: true,
                    type: 'base64'
                }) :
                XLSX.writeFile(wb, fn || ('Order.' + (type || '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

JavaScript node_modules import issue

I've been grappling with this issue for quite some time now. The problem lies in the malfunctioning of imports, and I cannot seem to pinpoint the exact reason behind it. Let me provide you with a few instances: In my index.html file, which is complet ...

Changing a string into a JavaScript date object

I am encountering an issue where I have a string retrieved from a JSON object and attempting to convert it to a JavaScript date variable. However, every time I try this, it returns an invalid date. Any insights into why this might be happening? jsonObj["d ...

Transforming JSON/XML into a hierarchical display

I've come across the following XML file: <Person attribute1="value1" attribute2="value2"> value3 <Address street="value4" city="value5">value6</Address> <Phone number="value7" type="value8">value9</Phone> </Pers ...

React Native: How come my text is breaking like this and failing to adhere to the container's margin settings?

I am facing a challenge in React Native where I need to display multiple elements next to each other, with a flex wrap when there are too many elements or if the text is too long. Each element consists of an icon and text, with the text breaking into the n ...

What is the best way to choose an Animatedmodal that can showcase various demos while using just one ID?

I am currently customizing my website and utilizing the AnimatedModal.js framework. I have successfully displayed content in one modal, but encountered difficulty when attempting to create multiple modals as they all share the same ID. My question is, how ...

Ways to position cursor at the end in the Froala Editor

My current dilemma involves the need to position the focus/cursor at the end of text that is loaded within the Froala editor. I attempted to accomplish this using the focus event of Froala (events.focus), but unfortunately, it did not yield the desired out ...

Steps to create a new window using Raphael JS

Is there a way to create a new window in Raphael similar to using "_blank"? ...

Looking to retrieve the raw HTTP header string in Node.js using express.js?

Currently, I am utilizing Node.js and express.js for my work. The project I am currently working on requires me to access the raw strings of the HTTP headers (charset and accepted). In express.js, there is a function available that can provide the charset ...

It's possible for anyone to enhance the appearance of the Download button by adding styles without compromising its functionality

Looking to enhance the style of the Download button as it appears too formal. Seeking assistance in adding some button styles to make it more stylish. The code is correct, just aiming to give the Download button a trendy look with specified styles. ...

Tips for expanding an input field to span across two td elements

I am attempting to design a simple form. The issue I am encountering involves creating an input field that spans two td's in the second row of my table. Despite using the colspan="2" attribute within the td tag, the input field does not expand over tw ...

Varying heights based on the screen size

Currently, I am in the process of designing my website and incorporating some wave elements to enhance the background. However, I've encountered some issues when resizing the screen. Specifically, the waves seem to shift with a space between them as t ...

Iterate over an array in JavaScript and include the elements as parameters in an SQL query

Can I set an SQL string to a variable in JavaScript and populate part of it by looping through an array? Here is the initial SQL: var tag = ["fun", "beach", "sun"]; var sql = "SELECT * FROM myTable " +"WHERE id > 5" //... // L ...

What is the best way to convert a Date into the JSON format before sending it to the database?

I'm currently delving into backend development with Node.js, and I am in the process of connecting my backend to a MongoDB. Specifically, I am working on creating a User object that includes Birth Date as one of its properties. However, I am strugglin ...

Update the message displayed in the user interface after the view has been fully rendered in an Express application, following the execution of asynchronous

I have created a simple express app that reads files from a directory, renames them, zips the files asynchronously, and then renders another view. The file reading and renaming are done synchronously, while the zipping part is handled asynchronously. My cu ...

How to update MongoDB documents with referenced objects using Mongoose?

Apologies for any language barriers. I am using node.js + express.js + mongoose.js Here is my schema in mongoose for groups: var groupSchema = new mongoose.Schema({ name: String, users: [{type: mongoose.Schema.ObjectId, ref: 'User'}] ...

The value calculated by Auto does not display as a valid number in Angular 8 until it has been manually edited

Having an issue with a form submission for invoicing. The total value field, which is auto-calculated based on quantity and unit price, does not show up as numeric data in the backend onSubmit event unless I manually interact with it by adding something ...

Mastering the art of managing promises within nested loops

Embarking on my Promise journey, I find myself faced with a scenario where a list of objects within another list of objects needs to be updated based on responses from an external API. I've attempted to simulate the scenario below. The code snippet f ...

When retrieving data from a PHP $_SESSION using an Ajax $_POST call, outdated information is being returned

I am encountering an issue that I cannot seem to figure out. Currently, my application consists of three pages: Home.php Nearmiss.php Reports.php Each of these pages includes code at the top with a specific "thispage" variable unique to that page. < ...

Is it possible for style sheets to malfunction due to the presence of the TITLE attribute on <link> tags?

We are currently involved in the process of upgrading an outdated corporate intranet. The challenge is that our users primarily rely on IE8 and IE9, while most of our sites were designed to function with compatibility for browsers between IE5 - IE9. While ...

Display or conceal HTML content based on the input's property type

Looking to toggle the visibility of an icon on my input based on the prop type. If the type is set to password, the icon will be displayed for toggling between visible and hidden password; if the type is not password, the icon should be hidden by setting ...