Exporting Datatable to Excel may cause line breaks

I have structured my project in the following manner: https://jsfiddle.net/Eufragio/u342qgoz/1/

When I export to excel, I require a better layout or a more visible method to display my results

 $(document).ready( function () {
  var table = $('#example').DataTable({
    dom: 'Btirp',
    buttons: [{
    extend: 'csvHtml5',
    text: 'CSV',
    filename: 'csv_file',
    footer: true
    },
    {
    extend: 'excelHtml5',
    text: 'Excel',
    filename: 'excel_file',
    footer: true
    }],
      //Total General

    "footerCallback": function (row, data, start, end, display) {
        var api = this.api(),
          data;

        // Function to convert data to integer for summation
        var intVal = function (i) {
            return typeof i === 'string' ?
              i.replace(/[\L,]/g, '') * 1 :
              typeof i === 'number' ?
                i : 0;
        };

        /*
   // Total over all pages
   total = api
     .column(5)
     .data()
     .reduce(function(a, b) {
       return intVal(a) + intVal(b);
     }, 0);

   // Total over this page
   pageTotal = api
     .column(5, {
       page: 'current'
     })
     .data()
     .reduce(function(a, b) {
       return intVal(a) + intVal(b);
     }, 0);

   // Update footer
   $(api.column([5, 3]).footer()).html(
     // '' + pageTotal + ' ( L' + total + ' total)'
     //'' + total.toFixed(2)
     '' + total

   );
   */



        // Total over all pages
        total = api
          .column(3)
          .data()
          .reduce(function (a, b) {
              return intVal(a) + intVal(b);
          }, 0);

        // Total over this page
        pageTotal = api
          .column(3, {
              page: 'current'
          })
          .data()
          .reduce(function (a, b) {
              return intVal(a) + intVal(b);
          }, 0);

        // Update footer
        $(api.column(3).footer()).html(
          // '' + pageTotal + ' ( L' + total + ' total)'
          //'' + total.toFixed(2)
          '' + total

        );
    },

    "columnDefs": [{
        "visible": false,
        "targets": 2
    }],
    "order": [
      [2, 'asc']
    ],
    "displayLength": 25,
    "drawCallback": function (settings) {
        var api = this.api();
        var rows = api.rows({
            page: 'all'
        }).nodes();
        var last = null;

        // Function to convert data to integer for summation
        var intVal = function (i) {
            return typeof i === 'string' ?
              i.replace(/[\$,]/g, '') * 1 :
              typeof i === 'number' ?
                i : 0;
        };
        var groupTotal = {};
        api.column(2, {
            page: 'all'
        }).data().each(function (group, i) {
            group_assoc = group.replace(' ', "_");
            console.log(group_assoc);
            if (typeof groupTotal[group_assoc] != 'undefined') {
                groupTotal[group_assoc] = groupTotal[group_assoc] + intVal(api.column(5).data()[i]);

                /*
       $(api.column(2).footer()).html(

         '' + total[group_assoc]

       );
       */

            } else {
                groupTotal[group_assoc] = intVal(api.column(5).data()[i]);
            }
            if (last !== group) {
                $(rows).eq(i).before(
                  '<tr class="group"><td colspan="4">' + group + '</td><td class="' + group_assoc + '"></td></tr>'
                );

                last = group;
            }
        });

        var footerText = [];
        var footerTotal = [];
        for (var key in groupTotal) {
            $("." + key).html("L" + groupTotal[key].toFixed(2));
            footerText.push(key);  
            footerTotal.push("L" + groupTotal[key].toFixed(2));  
        }
        $(api.column(4).footer()).html(
         footerText.join('<br>')
       );
        $(api.column(5).footer()).html(
         footerTotal.join('<br>')
       );




    }
  });


    });

My issue arises when I export to excel, as the generated results appear like this: https://i.sstatic.net/f8Yg2.png

The desired result that I am aiming for can be seen here: https://i.sstatic.net/3sfxN.png

How can I achieve this desired result? Do you have any recommendations on alternative methods to display the data?

Answer №1

An old issue, but perhaps someone is still searching for a solution. I encountered the same problem with DataTables version 1.10.10, which did not support the "\r\n" characters. After hours of searching, I finally found the solution – simply upgrading to the latest version of DataTables (1.10.20).

Now, everything is running smoothly with this updated code:

extend: 'excelHtml5',
filename: 'file_name',
text: 'Save as Excel',
exportOptions: {
    format: {
        body: function(data, column, row) {
            if (typeof data === 'string' || data instanceof String) {
                data = data.replace(/<br\s*\/?>/ig, "\r\n");
            }
            return data;
        }
    }
}

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

Using jQuery to iterate through rendered HTML with the ForEach function

I am utilizing JS/jQuery code to extract the cell value of an ASP DetailsView control (rendered HTML), validate it against a condition, and hide a specific div based on the result. Specifically, the code is examining whether the cell value is formatted lik ...

Using Ionic to invoke a function within another function in a JavaScript service

Hey everyone, I've come across an issue while working on my Ionic mobile app project. I need to call a function within another function in one of my service.js files (pushNotificationService.js). Here is the code snippet: checkForNewMessage: functi ...

Sending JSON data back to React in a file format

I have a json file within the project that contains the necessary data to display in my component. Can someone guide me on how to properly access the json file in react and output the data from it? data.json { "dictionary": [ { "index": "1", ...

Running a child process within a React application

I'm currently in search of the best module to use for running a child process from within a React application. Here's what I need: I want a button that, when clicked, will execute "npm test" for my application and generate a report that can be r ...

How to build a registration form with Stateless Components?

Could someone provide a sample code or explanation on how to create a form using stateless components? I'm also in need of a Material UI form example that utilizes refs. Please note that I am working with Material UI components. Below is the curren ...

Discovering the total number of tickets based on priority in an array with Javascript

I have the following data set { agent_id:001, priority:"High", task_id:T1 }, { agent_id:001, priority:"High", task_id:T1 }, { agent_id:001, priority:"Medium", task_id:T1 } { agent_id:002, priority:"High", task_id:T1 ...

Stack the labels of separate datasets on top of each bar in a bar chart using Chartjs: How can this be achieved?

chart.js 4.4.2 chartjs-plugin-datalabels I am aiming to achieve this effect const chartCtr = document.querySelector('#temp-chart1') as HTMLCanvasElement; new Chart(chartCtr, { type: 'line', plugins: [ChartDataLabels], opt ...

Utilizing Kerberos Authentication in ASP.NET HttpWebRequest

I have been attempting to establish a connection with a web service that utilizes Kerberos Authentication for user authorization. However, every time I make the request, I receive a 401 unauthorized error. Below is the code snippet that I am currently util ...

Storing Documents on Your Device

I've been working on a project to create a web page that provides links to online PDF files. When you click on these links, the file should be saved locally and its name/path added to local storage. I then aim to display all the saved files by iterati ...

Issue detected in React Rollup: the specific module 'name' is not being exported from the node_modules directory

Currently in the process of creating a library or package from my component. The tech stack includes React, Typescript, and various other dependencies. Encountering an error while using Rollup to build the package: [!] Error: 'DisplayHint' is ...

real-time update of gauge value from soap

I am trying to update the value shown in my justgage widget with the value returned from $("#spanrWS_Measured").text(data[0]);. The current value is 123. Any assistance would be greatly appreciated. See the complete code below. <script src="scripts/r ...

What is the method for automatically verifying elements within nested ng-repeats?

My div contains ng-repeat elements that are interconnected. Each ng-repeat element has checkboxes, and I want to automatically check the related elements in other ng-repeats when a top ng-repeat element is checked. Here is the actual representation of the ...

AJV is failing to validate my body using the function generated by the compile method

Currently, in my API development process with express, I have implemented AJV as a middleware to validate the incoming body data. The version of AJV being used is 6.12.6 Below is the JSON schema named body-foobar.json: { "type": "object& ...

JavaScript date input formatting with HTML

When using the input date picker in HTML, the default format displayed is MM-DD-YYYY. <input type="date" id="gdatum" /> Is there any method to change the mask to DD-MM-YYYY? ...

How to Call a Nested Object in JavaScript Dynamically?

var myObj = { bar_foo : "test", bar : { foo : "hi there"; }, foo : { bar : { foo: "and here we go!" } } } How can we achieve the following: var arr = [["bar", "foo"], ...

The functionality of AngularJS's state URL depends on numerical URLs for navigation

Currently, I am utilizing the following URL in my state setup: .state('forum.spesific', { url: '/:articleId', templateUrl: 'modules/forum/client/views/forum.client.view.html', controller: 'forumCont ...

What is the process for the event loop moving into the poll phase?

There is a scenario outlined in the event loop explanation on the Node.js official website. When setTimeout is triggered, and the callback queue for the timer phase isn't empty, why does the event loop move on to the poll phase? The site mentions that ...

How can I effectively separate the impact of Next.js onChange from my onClick function?

The buttons in my code are not functioning properly unless I remove the onChange. Adding () to my functions inside onClick causes them to run on every keystroke. How can I resolve this issue? In order to post my question, I need to include some dummy text. ...

The addDays method cannot be used with date variables

Having two TextBoxes where I input 2 dates and try to retrieve an array of dates between them. Here is the code I'm using: $(".txtto").change(function () { var dates = new Array(); var dateto = new Date(); ...

Transfer PDF file to user's web browser through XMLHttpRequest, utilizing up-to-date HTML5 techniques, all while maintaining the integrity of the document's encoding

I am trying to achieve a similar result as described in this StackOverflow post about handling file download from ajax post. However, I'm working with a dynamically-generated PDF file created using PHP v5.6.10 (with the PDFLib extension, v9.0.5). Unf ...