How can I use Jquery to export content from a div into separate rows and cells in an Excel document

I am having trouble exporting div data using Jquery. The values are all appearing in the same cell.

Check out the initial example image:

https://i.sstatic.net/6weMh.png

Now, take a look at the desired example image:

https://i.sstatic.net/LCjp4.png

I must have missed something in my code. Any assistance is appreciated.

JS:

var csvContent = "First Name, Middle Name, Last Name"; // CSV file headers

var dataElements = document.getElementsByClassName("sample");
for (var i = 0; i < dataElements.length; i++) {   
// Iterating through each data entry
var entryLineCsv = document.getElementById("kaf70").innerHTML + "," 
                 + document.getElementById("kaf71").innerHTML + ","
                 +document.getElementById("kaf72").innerHTML + ",";  
createCsvFile(entryLineCsv);
 }

 function createCsvFile(addEntryLineIoCsv) {

  let file = new Blob([csvContent = csvContent + addEntryLineIoCsv], { type: "application/vnd.ms-excel" });

    let url = URL.createObjectURL(file);

   let a = $("<a />", {

        href: url,

        download: "filename.xls"

    }).appendTo("body").get(0).click();


 }

HTML:

div class="losSection" id="secReviewerDemographics"><div class="losSectionHeader"><div class="losSectionSel losSectionTitle misign" data-originaltitle="Demographics">Demographics</div></div><div id="cpC_kf_secview_50" class="losSectionView"><div>



   <div id="ExportDetails" class="sample">

      <div class="tabularView">

         <input type="hidden" name="kaf_78" id="kaf_78" aria-label="kaf_78" value="01" class="._shCE"> 

         <div id="cpC_ctl73" class="tabularTbl flex-row start-xs">

           <div class="pad1x flex-row leftLblMode">

               <div class="pad1x flex-col-xs-12 flex-col-sm-6">

                  <div style="">

                     <label for="kaf_70" id="klb_70" class="input-control-label input-control-label input-control-label input-control-label input-control-label input-control-label">First Name

                     </label>

                  </div>

               </div>

               <div class="pad1x flex-col-xs-12 flex-col-sm-6">

                  <div class="labelValueField">

                     <span class="labelValue" name="kaf_70" id="kaf_70">

                        <span class="labelValue" name="kaf_70" id="kaf70" aria-label="Applicant First Name">NAMA</span>

                     </span>

                  </div>

               </div>

            </div>

            <div class="pad1x flex-row leftLblMode">

               <div class="pad1x flex-col-xs-12 flex-col-sm-6">

                  <div style="">

                     <label for="kaf_71" id="klb_71" class="input-control-label input-control-label input-control-label input-control-label input-control-label input-control-label">Middle Name</label>

                  </div>

               </div>

               <div class="pad1x flex-col-xs-12 flex-col-sm-6">

                  <div class="labelValueField">

                     <span class="labelValue" name="kaf_71" id="kaf_71">

                        <span class="labelValue" name="kaf_71" id="kaf71" aria-label="Applicant Middle Name">VEENESH</span>

                     </span>

                  </div>

               </div>

            </div>

            <div class="pad1x flex-row leftLblMode">

               <div class="pad1x flex-col-xs-12 flex-col-sm-6">

                  <div style="">

                     <label for="kaf_72" id="klb_72" class="input-control-label input-control-label input-control-label input-control-label input-control-label input-control-label">Last Name

                     </label>

                  </div>

               </div>

               <div class="pad1x flex-col-xs-12 flex-col-sm-6">

                  <div class="labelValueField">

                     <span class="labelValue" name="kaf_72" id="kaf_72">

                        <span class="labelValue" name="kaf_72" id="kaf72" aria-label="Applicant Last Name">KUMAR</span>

                     </span>

                  </div>

               </div>

            </div>



         </div>

         </div>

   </div>




                </div></div>

    <button id="ExportToExcel" onclick="exportF(this)">Export To Excel</button>     

DEMO Code: DEMO LiNK

Answer №1

You are encountering two problems here. Firstly, the syntax used to create the Blob is incorrect as there is no data provided within the expression. Additionally, trying to generate an XLS file in plain text format will not work effectively given the nature of that file type.

A simpler approach would involve creating a CSV file instead, aligning with the way strings are formatted. Each line should be separated by a line break to maintain structure.

For those utilizing jQuery, you can streamline the data retrieval process by leveraging nested map() calls to form an array for each output line. Consider the following code snippet:

let csv = $('.sample').map((i, sample) => {
  return $(sample).find('span > .labelValue').map((_, field) => field.innerText).get().join(',');
}).get();
csv.unshift('First Name,Middle Name,Last Name'); // include headers
createCsvFile(csv);

function createCsvFile(csvArray) {
  let file = new Blob([csvArray.join('\r\n')], { type: "application/csv" });
  let url = URL.createObjectURL(file);
  let a = $("<a />", {
    href: url,
    download: "filename.csv"
  }).appendTo("body").get(0).click();
}

Demonstration of Solution

Please note that additional lines have been included in the jsFiddle example to showcase its scalability.

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

Leveraging directives within AngularJS

I'm currently delving into the world of AngularJS and facing a particular question that has me stumped. Let's examine the sample code snippet I put together: js var app = angular.module('customerPortalApp', ["ui.router"]); app.confi ...

The JavaScript switch statement is malfunctioning

I am facing an issue with a switch statement in my code. The switch has multiple cases that compare values and assign a corresponding text to a variable. However, when I run the switch statement, it always executes the default case even though my condition ...

Tips for managing multiple ng-show and one ng-hide in AngularJS: when one condition is true, set the ng-show for that condition to true and the rest to false

Whenever a user hovers over the stars, my goal is to display the message You rated <b>{{rate1}} star.</b><a ng-click="showMe()" class="modifyIt"><b > modify?</b></a>. If the user has already clicked on the rating, I wan ...

Steps to insert a column within an HTML document for PDF printing

Is there a way to create an HTML document that can be printed in PDF format but the column feature isn't functioning as expected? Would I need to use a specific library or tool? ...

Setting a specific 30-second interval for the datetime on the y-axis in Highcharts JS

I need to create a graph where the y-axis represents time in 30-second intervals, ranging from 2:00 to 5:30. The data I have is in seconds and I want to display it on the graph accordingly. I came across an example that displays time in hours and minutes, ...

CSS can always surprise with its unexpected animations

Currently developing a static website with CSS animations: * { -webkit-transition: all 1s ease-in-out; -moz-transition: all 1s ease-in-out; -o-transition: all 1s ease-in-out; -ms-transition: all 1s ease-in-out; transition: all 1s ease- ...

What are the reasons and methods for cleaning up components in React JavaScript?

While I comprehend the necessity of tidying up our components in React to avoid memory leaks (among other reasons), as well as knowing how to utilize comonentWillUnmount (which is outdated) and the useEffect hook, my burning question remains: what exactl ...

The module script failed to load due to an unexpected response from the server, which was MIME type of text/jsx instead of a javascript module script

I have recently set up an express server and created an API, as well as installed React using Vite for my frontend. However, when I attempt to connect or load my main HTML file to the server, an error is displayed in the console. This is all new to me as I ...

Transforming HTML div elements into a PHP array

I am trying to work with HTML code that consists of multiple div elements, each containing a different source. <div class="moviefilm"> SURSA 1 </div> <div class="moviefilm"> SURSA 2 </div> <div class="moviefilm"> SURSA 3 &l ...

Requesting data from a REST API using a nested query in a GET

After querying data from my MongoDB database, I am faced with the challenge of sending a GET request from the front end to meet this specific query. In my backend code, I retrieve the data using the following: const products = await Product.find({ &apo ...

Is it possible to dynamically load a PHP plugin in WordPress using jQuery and AJAX?

Is there a way to dynamically load a WordPress plugin shortcode using jQuery, Ajax, and PHP only when a specific button is clicked? Here's what I have attempted: 1) I've created an HTML snippet with a button and a DIV container: <a href="#" ...

The statement "document.getElementById('grand_total_display').innerHTML = "Total is : $"+variable;" is causing issues in Internet Explorer versions 6 and 7

document.getElementById('grand_total_display).innerHTML = "Total is : $"+variable; seems to be causing an error specifically in IE6 and IE7 Within my HTML, I have an element <li> identified as grand_total_display which contains some existing te ...

The ng-repeat directive is utilized to iterate through the children of the $scope object

There has been some discussion on whether it is better to use a child object on a scope instead of adding directly to the scope itself. For example: $scope.model.mystuff is said to be better than $scope.mystuff Surprisingly, my first simple code snipp ...

Error is thrown when attempting to access nested elements using GetElementsByClassName within the window.onload function

I have a funky looking table on my webpage, here's an example: <body> <table class="table table-bordered"> <thead> <tr> <th>#</th> <th>Product name</th> <th>Product ...

The functionality to apply a color class to a navbar item when clicked is malfunctioning

I'm attempting to create a navigation bar using text that toggles the visibility of different divs. I want the selected option to appear in red, indicating it has been chosen, while deselecting any other options. I am new to JavaScript and thought add ...

What causes a div to shift to the right when the margin-left is set to auto?

I am curious to understand why setting the margin-left of the div with id="pink" to auto causes the div to move to the right side. Take a look at the image below: HTML <div id="aqua">aqua</div> <div id="yellow">yellow</div> & ...

SignalR is experiencing an issue with a protocol error that is related to an unknown

I've been trying to implement the concepts from this article on SignalR and Knockout.js, but I'm encountering some issues. Here is the article I am referencing: http://www.codeproject.com/Articles/322154/ASP-NET-MVC-SIngalR-and-Knockout-based-Re ...

How to Build Node 0.4.7 on Ubuntu 11.10?

Having trouble compiling 0.4.7 for Heroku support as I am unable to enable ssl support required by express. I've tried installing libssl-dev and even attempted manual installation of openssl, but no luck so far. Any suggestions on how to get node up a ...

Implementing filters for varying key values within an array of Objects in React Native

I'm looking to implement a filter on an array containing objects and I want to be able to search based on country, name, or value in the search bar and retrieve results related to that specific query. Can you please guide me on how to achieve this? Cu ...

What steps should be taken to incorporate a user input space similar to the one found in the Wordpress new post section

I am looking to incorporate a user input section on my website similar to the one found in WordPress for creating new posts. I would like this area to have all of the same tools available, such as adding hyperlinks, bolding text, and uploading images. Ca ...