Search code examples
javascriptjquerydatatable

add serial number column in datatable pdf export


I am working on e-commercial project using html and javascript in my project. As a part I need to show the details of product ordered. I am using Jquery datatable inorder show the details. I need to export the details from datatable to excel and using. this all works fine but the problem is I need to add serial number while exporting I tried several ways. Below is the export buttons

buttons: [
        {
          extend: "excel",
          footer: true,
          title: "my report",
          exportOptions: {
            columns: [1, 2, 3, 4],
          },
        },
        {
          extend: "pdf",
          footer: true,
          title: "my report",
          exportOptions: {
            columns: [1, 2, 3, 4],
          },
        },
      ]

I added my zero th column along with the pdf export. but this fails while export the pdf after filtering

please help me to solve this huddle? if any clarity need please comment I will do my best


Solution

  • you can use custom fields in Datatable while exporting to PDF or Excel by using the below code.

    buttons: [
            {
              extend: "excel",
              footer: true,
              title: "my report",
              exportOptions: {
                columns: [1, 2, 3, 4],
              },
            },
            {
              extend: "pdf",
              footer: true,
              title: "my report",
              exportOptions: {
                columns: [1, 2, 3, 4],
              },
              customize: function (doc) {
                var col = doc.content[1].table.body;
                for (i = 1; i < col.length; i++) {
                  col[i][0]["text"] = i;
                }
              },
            },
          ]