2016-12-09 3 views
1

DataTables를 대체하기 위해 jqGrid를 설정했지만 Excel로 내보내기 기능 중 하나가 부족합니다. DataTables는 이것을 html5로 처리하고 플래시를 백업 방법으로 사용합니다 (플래시를 전혀 사용하지 않으려합니다).jqGrid - PHP 서버가 포함 된 Excel로 내보내기

jqGrid를 사용하여이를 수행 할 방법을 검색 할 때 꽤 오래된 몇 개의 게시물이 있지만 최근의 게시물은 없습니다. JSON 파일에서 가져온 데이터와 함께 PHP 서버 백엔드를 사용하고 있습니다. jqGrid의 유료 버전에는 PHP 버전이 있습니다. 실제 Excel 파일 (csv가 아닌)을 내보내는 데 사용할 수있는 무료 버전의 jqGrid와 호환되는 메서드가 있습니까? 엑셀 함수에 수출 양식 입력

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

자바 스크립트를있는 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에 대한

+0

[이 가까운 솔루션 (https://github.com/kayalshri/tableExport.jquery.plugin) 다른 플러그인을 사용하지만, 같은 파일 이름을 지정 할 수없는, 아니 테이블로있는 jqGrid와 몇 가지 문제가 있습니다 헤더 및 현재 데이터 만 내보낼 수 있습니다. – MarkT

답변

2

버튼

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){ 

} 
1

내가 만든 내부 사이트에도 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