【问题标题】:jqGrid - Export to Excel with PHP serverjqGrid - 使用 PHP 服务器导出到 Excel
【发布时间】:2017-04-24 09:43:27
【问题描述】:

我已将 jqGrid 设置为 DataTables 的替代品,但我缺少的一个重要部分是导出到 Excel 的能力。 DataTables 使用 html5 处理这个问题,并使用 Flash 作为备份方法(我根本不想使用 Flash)。

在寻找使用 jqGrid 执行此操作的方法时,我看到了几篇相当老的帖子,但都不是最近的。我正在使用来自 JSON 文件的数据的 php 服务器后端。我看到 jqGrid 的付费版本有一个 php 版本。有没有一种与 jqGrid 的免费版本兼容的方法可以用来导出真正的 Excel 文件(不是 csv)?

【问题讨论】:

  • This is a close solution 使用另一个插件,但 jqGrid 存在一些问题,例如无法指定文件名、没有表头以及仅导出当前页面的数据。

标签: php jquery excel jqgrid free-jqgrid


【解决方案1】:

jqGrid 按钮

 $grid.jqGrid("navButtonAdd", {
            caption: "Export<br />To Excel",
            buttonicon: "ui-pg-button-text ui-pg-button-icon-over-text fa-file-excel-o",
            title: "Export to Excel",
            onClickButton: function () {
                exportExcel();
            }
        });

表单输入的 HTML

       <form id='_export' method="post" action="jqGrid/export_excel.php">
                    <input type="hidden" name="csvBuffer" id="csvBuffer" value="" />
        </form>

JAVASCRIPT 导出到 Excel 功能

function exportExcel()
{
        var keys=[], ii=0, rows="";
                  var ids=$("#list").getDataIDs(); 
                  var row=$("#list").getRowData(ids[0]);     
                  var p = $("#list").jqGrid("getGridParam");
                  var rows="<table><thead><tr>";
                  for (var k in row) {
                    keys[ii++]=k;   
                    rows=rows+'<th>'+p.colNames[ii+1]+'</th>';    
                  }
                  rows=rows+"</tr></thead><tbody>";  
                  for(i=0;i<ids.length;i++) {
                    row=$("#list").getRowData(ids[i]); 
                    rows=rows+"<tr>";
                    for(j=0;j<keys.length;j++){
                        rows=rows+'<td>'+row[keys[j]]+'</td>'; 
                    }
                    rows=rows+"</tr></tbody>"; 
                  }
                  rows=rows+"</table>";
    document.getElementById('csvBuffer').value=rows;
    document.getElementById('_export').submit();
}

用于下载 XLS 文件的 PHP

$buffer = $_POST['csvBuffer'];

  // file name for download
  $filename = "baplie_" . date('Ymd') . ".xls";

  header("Content-Disposition: attachment; filename=\"$filename\"");
  header("Content-Type: application/vnd.ms-excel");

try{
    echo $buffer;
}catch(Exception $e){

}

【讨论】:

    【解决方案2】:

    我也将 DataTables 用于我创建的内部网站。我使用此脚本将表数据下载到 CSV 文件,效果很好。您可能需要更改一些内容以使 Id 和类与您的表匹配,但请尝试一下。

        // export data function    
    $('#exportDataTable').click(function() {
      var titles = [];
      var data = [];
     /* * Get the table headers, this will be CSV headers
       * The count of headers will be CSV string separator */
      $('.dataTable th').each(function() {
        titles.push($(this).text());
      });
    /* * Get the actual data, this will contain all the data, in 1 array */
      $('.dataTable td').each(function() {
        data.push($(this).text());
      });
    /* * Convert our data to CSV string */
      var CSVString = prepCSVRow(titles, titles.length, '');
      CSVString = prepCSVRow(data, titles.length, CSVString);
    /* * Make CSV downloadable*/
      var downloadLink = document.createElement("a");
      var blob = new Blob(["\ufeff", CSVString]);
      var url = URL.createObjectURL(blob);
      downloadLink.href = url;
      downloadLink.download = "data.csv";
    /** Actually download CSV */
      document.body.appendChild(downloadLink);
      downloadLink.click();
      document.body.removeChild(downloadLink);
    });
    /** Convert data array to CSV string
    * @param arr {Array} - the actual data
    * @param columnCount {Number} - the amount to split the data into columns
    * @param initial {String} - initial string to append to CSV string
    * return {String} - ready CSV string */
    function prepCSVRow(arr, columnCount, initial) {
      var row = ''; // this will hold data
      var delimeter = ','; // data slice separator, in excel it's `;`, in usual CSv it's `,`
      var newLine = '\r\n'; // newline separator for CSV row
    /* * Convert [1,2,3,4] into [[1,2], [3,4]] while count is 2
       * @param _arr {Array} - the actual array to split
       * @param _count {Number} - the amount to split
       * return {Array} - splitted array */
      function splitArray(_arr, _count) {
        var splitted = [];
        var result = [];
        _arr.forEach(function(item, idx) {
          if ((idx + 1) % _count === 0) {
            splitted.push('"' + item + '"');
            result.push(splitted);
            splitted = [];
          } else {
            splitted.push('"' + item + '"');
          }
        });
        return result;
      }
      var plainArr = splitArray(arr, columnCount);
      // don't know how to explain this
      // you just have to like follow the code
      // and you understand, it's pretty simple
      // it converts `['a', 'b', 'c']` to `a,b,c` string
      plainArr.forEach(function(arrItem) {
        arrItem.forEach(function(item, idx) {
          row += item + ((idx + 1) === arrItem.length ? '' : delimeter);
        });
        row += newLine;
      });
      return initial + row;
    } 
    // end export to CSV file
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多