Как экспортировать DataTable в Excel с формулой SUM - PullRequest
0 голосов
/ 20 апреля 2020

Я искал способ экспорта данных в Excel с формулой sum. Я нашел несколько примеров, связанных с этим, но я не мог правильно понять этот код. Точно так же, как этот

        <!DOCTYPE html>
        <html>

        <head>
          <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/jq-3.2.1/jszip-2.5.0/dt-1.10.16/b-1.5.1/b-html5-1.5.1/b-print-1.5.1/datatables.min.css" />

          <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.32/pdfmake.min.js"></script>
          <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.32/vfs_fonts.js"></script>
          <script type="text/javascript" src="https://cdn.datatables.net/v/dt/jq-3.2.1/jszip-2.5.0/dt-1.10.16/b-1.5.1/b-html5-1.5.1/b-print-1.5.1/datatables.min.js"></script>
          <meta charset=utf-8 />
          <title>DataTables - JS Bin</title>
        </head>

        <body>
          <div class="container">
            <table id="example" class="table table-bordered display" cellspacing="0" width="100%">
              <thead>
                <tr>
                  <th>COL 1</th>
                  <th>COL 2</th>
                  <th>COL 3</th>
                  <th>COL 4</th>
                </tr>
              </thead>
              <tbody>

                <tr>
                  <td>
                    <div class="form-group">LINE 1</div><br>LINE 2
                  </td>
                  <td>
                    <p>LINE 3</p>
                    <p>LINE 4</p>
                  </td>
                  <td>LINE 5</td>
                  <td>
                    <div class="form-group">LINE 6</div>LINE 7
                  </td>
                </tr>

                <tr>
                  <td>
                    <div class="form-group">LINE 1</div><br>LINE 2<br>LINE 3<br>LINE 4<br>LINE 5
                  </td>
                  <td>
                    <p>LINE 3</p>
                    <p>LINE 4</p>
                  </td>
                  <td>LINE 5</td>
                  <td>
                    <div class="form-group">LINE 6</div>LINE 7
                  </td>
                </tr>

              </tbody>
            </table>
          </div>
        </body>

        </html>

// Excel part
        <script>
          function columnToLetter(column) {
            var temp, letter = '';
            while (column > 0) {
              temp = (column - 1) % 26;
              letter = String.fromCharCode(temp + 65) + letter;
              column = (column - temp - 1) / 26;
            }
            return letter;
          }

          function remove_tags(html) {
            html = html.replace(/<br>/g, "$br$");
            html = html.replace(/(?:\r\n|\r|\n)/g, '$n$');
            var tmp = document.createElement("DIV");
            tmp.innerHTML = html;
            html = tmp.textContent || tmp.innerText;

            html = html.replace(/\$br\$/g, "<br>");
            html = html.replace(/\$n\$/g, "<br>");

            return html;
          }

          $(document).ready(function() {
            var table = $('#example').DataTable({
              dom: 'Btirp',
              buttons: [{
                extend: 'excelHtml5',
                text: 'Excel',
                exportOptions: {
                  format: {
                    body: function(data, row, column, node) {

                      //need to change double quotes to single
                      data = data.replace(/"/g, "'");

                      // replace p with br
                      data = data.replace(/<p[^>]*>/g, '').replace(/<\/p>/g, '<br>');

                      // replace div with br
                      data = data.replace(/<div[^>]*>/g, '').replace(/<\/div>/g, '<br>');

                      data = remove_tags(data);



                      //split at each new line
                      splitData = data.split('<br>');

                      //remove empty string
                      splitData = splitData.filter(function(v) {
                        return v !== ''
                      });

                      data = '';
                      for (i = 0; i < splitData.length; i++) {
                        //add escaped double quotes around each line
                        data += '\"' + splitData[i] + '\"';
                        //if its not the last line add CHAR(13)
                        if (i + 1 < splitData.length) {
                          data += ', CHAR(10), ';
                        }
                      }

                      //Add concat function
                      data = 'CONCATENATE(' + data + ')';
                      return data;

                    }
                  }
                },
                customize: function(xlsx) {

                  var sSh = xlsx.xl['styles.xml'];

                  var styleSheet = sSh.childNodes[0];

                  cellXfs = styleSheet.childNodes[5];

                  // Using this instead of "" (required for Excel 2007+, not for 2003)
                  var ns = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";

                  // Create a custom style
                  var lastStyleNum = $('cellXfs xf', sSh).length - 1;
                  var wrappedTopIndex = lastStyleNum + 1;
                  var newStyle = document.createElementNS(ns, "xf");
                  // Customize style
                  newStyle.setAttribute("numFmtId", 0);
                  newStyle.setAttribute("fontId", 0);
                  newStyle.setAttribute("fillId", 0);
                  newStyle.setAttribute("borderId", 0);
                  newStyle.setAttribute("applyFont", 1);
                  newStyle.setAttribute("applyFill", 1);
                  newStyle.setAttribute("applyBorder", 1);
                  newStyle.setAttribute("xfId", 0);
                  // Alignment (optional)
                  var align = document.createElementNS(ns, "alignment");
                  align.setAttribute("vertical", "top");
                  align.setAttribute("wrapText", 1);
                  newStyle.appendChild(align);
                  // Append the style next to the other ones
                  cellXfs.appendChild(newStyle);





                  var sheet = xlsx.xl.worksheets['sheet1.xml'];

                  var firstExcelRow = 3;

                  table.rows({
                    order: 'applied',
                    search: 'applied'
                  }).every(function(rowIdx, tableLoop, rowLoop) {

                    var node = this.node();

                    var num_colonne = $(node).find("td").length;

                    // the cell with biggest number of line inside it determine the height of entire row
                    var maxCountLinesRow = 1;


                    for (var indexCol = 1; indexCol <= num_colonne; indexCol++) {

                      var letterExcel = columnToLetter(indexCol);

                      $('c[r=' + letterExcel + (firstExcelRow + rowLoop) + ']', sheet).each(function(e) {



                        // how many lines are present in this cell?
                        var countLines = ($('is t', this).text().match(/\"/g) || []).length / 2;

                        if (countLines > maxCountLinesRow) {
                          maxCountLinesRow = countLines;
                        }

                        if ($('is t', this).text()) {
                          //wrap text top vertical top
                          $(this).attr('s', wrappedTopIndex);

                          //change the type to `str` which is a formula
                          $(this).attr('t', 'str');
                          //append the concat formula
                          $(this).append('<f>' + $('is t', this).text() + '</f>');
                          //remove the inlineStr
                          $('is', this).remove();
                        }

                      });

                      $('row:nth-child(' + (firstExcelRow + rowLoop) + ')', sheet).attr('ht', maxCountLinesRow * 26);
                      $('row:nth-child(' + (firstExcelRow + rowLoop) + ')', sheet).attr('customHeight', 1);

                    }

                  });



                }

              }]

            });

          });
        </script>

после кода экспорта, который я поставил выше.

excel после кода экспорта, который я поставил выше.

и это Как я хочу, чтобы файл Excel был после экспорта.

Как я хочу, чтобы файл Excel был после экспорта

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...