2017-01-13 3 views
0

DataTables Server Side Processing을 사용하는보고 웹 사이트가 있습니다. 모든 것은 화면에 표시되는 부분뿐만 아니라 전체 데이터 세트를 내보낼 수 있어야한다는 점을 제외하고는 훌륭하게 작동합니다. 나는 10,000+ 행과 65+ 열을 갖는 보고서를 가지고 있으므로 페이지의 전체 보고서를 보지 못했습니다 (5 분 이상 걸리고 시간이 초과 될 것입니다). 나는 정말로 대답에 가까워 졌다고 생각하지만, 남은 부분을 얻는데 도움이 필요하다. 여기에 내가 가진 것 :JavaScript를 사용하여 내보낼 게시물을 통해 URL로 데이터 보내기

Excel 파일을 내보내는 데 PHPExcel 라이브러리를 사용하는 파일로 보내야하는 데이터를 수집하고 있습니다.

파일 (ExportAllToExcel.php)로 이동하면 정상적으로 작동하지만 버튼을 사용하여 데이터를 파일로 보내면 다운로드 할 수 없습니다. 여기에 내가 지금 가고있는 것이있다 :

$.fn.dataTable.ext.buttons.export = 
{ 
    className: 'buttons-alert', 
    id: 'ExportButton', 
    text: "Export All Test III", 
    action: function (e, dt, node, config) 
    { 
     var SearchData = dt.rows({ filter: 'applied' }).data(); 
     var OrderData = dt.order(); 
     var NumRow = SearchData.length; 
     var SearchData2 = []; 
     for (j = 0; j < NumRow; j++) 
     { 
      var NewSearchData = SearchData[j]; 
      for (i = 0; i < NewSearchData.length; i++) 
      { 
       NewSearchData[i] = NewSearchData[i].replace("<div class='Scrollable'>", ""); 
       NewSearchData[i] = NewSearchData[i].replace("</div>", ""); 
      } 
      SearchData2.push([NewSearchData]); 
     } 
     for (i = 0; i < SearchData2.length; i++) 
     { 
      for (j = 0; j < SearchData2[i].length; j++) 
      { 
       SearchData2[i][j] = SearchData2[i][j].join('::'); 
      } 
     } 
     SearchData2 = SearchData2.join("%%"); 

     //var SendPageData = new XMLHttpRequest(); 
     //SendPageData.open("POST", "./ExportAllToExcel.php", true); 
     //SendPageData.send('{NumRow=' + NumRow + '},{SearchData=' + SearchData2 + '}'); 
     $.post('./ExportAllToExcel.php',{SearchData: SearchData2,NumRow: NumRow}); 
     window.location.href = './ExportAllToExcel.php'; 
    } 
}; 

이것은 작동하지 않는다. $.POST은 데이터를 보내고 응답을 받지만 파일은 내 보내지 않습니다.

Window.location은 파일로 이동하여 Excel로 내 보내지만 $_POST의 데이터는 없으므로 파일에는 헤더 만 있습니다.

SendPageData$.POST과 같은 결과를 보내고 응답을 받지만 파일을 만들지 않습니다. 여기

그리고는 ExportAllToExcel.php입니다 :

<?php 
require $_SERVER['DOCUMENT_ROOT'].'/dev/Location/Helper/PageName.php';    //Pulls the Page name and Table name and returns the $SQLTableName, $TableName, $Title, $Page and $HeadingDesc 
include $_SERVER['DOCUMENT_ROOT'].'/dev/Location/DBConn.php';      //DB connection info 

$headings = array();      //Create the empty array for use later and so that it won't throw an error if not assinged later 
$hsql = "select Headings from TableHeadings where TableName = '$TableName' order by Id"; //Get all the column headers from the TableHeadings table in SQL 

$getHeadings = $conn->query($hsql); 
$rHeadings = $getHeadings->fetchALL(PDO::FETCH_ASSOC); 
$CountHeadings = count($rHeadings);   //Count how many columns that there will be 
$tsqlHeadings = ''; 
$ColumnHeader = array(); 
for ($row = 0; $row < $CountHeadings; $row++) 
{ 
    $headings[$row] = $rHeadings[$row]["Headings"];  //fill the array of column headings for use in creating the DataTable 
} 
print_r($headings); 

// Error reporting 
error_reporting(E_ALL); 
ini_set('display_errors', TRUE); 
ini_set('display_startup_errors', TRUE); 

if (PHP_SAPI == 'cli') 
    die('This example should only be run from a Web Browser'); 

// Add some data 
$ColumnArray = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ'); 
//$HeadingArray = array('Year','Quater','Country','Sales'); 
$HeadingArray = $headings; 

$primaryKey = 'id'; 
$table = $SQLTableName;     
$request = $_POST; 
$dataArray = array(); 
$dataArraystr = explode('%%',$_POST['SearchData']); 

foreach($dataArraystr as $ArrayStr) 
{ 
    $dataArray[] = explode('::',$ArrayStr); 
} 

// Include PHPExcel 
require_once dirname(__FILE__) . './Classes/PHPExcel.php'; 


// Create new PHPExcel object 
$objPHPExcel = new PHPExcel(); 

// Set document properties 
$objPHPExcel->getProperties()->setCreator("Michael McNair") 
          ->setLastModifiedBy("Michael McNair") 
          ->setTitle($TableName) 
          ->setSubject($TableName) 
          ->setDescription("Report for " .$TableName. " using PHPExcel, generated using PHP classes.") 
          ->setKeywords("office PHPExcel php " . $TableName) 
          ->setCategory("Report Export File"); 

$objPHPExcel->getActiveSheet()->fromArray($HeadingArray, NULL, 'A1'); 
$objPHPExcel->getActiveSheet()->fromArray($dataArray, NULL, 'A2'); 

$CountOfArray = count($HeadingArray); 
// Set title row bold 
$objPHPExcel->getActiveSheet()->getStyle('A1:' .$ColumnArray[$CountOfArray-1]. '1')->getFont()->setBold(true); 

// Set autofilter 
// Always include the complete filter range! 
// Excel does support setting only the caption 
// row, but that's not a best practise... 
$objPHPExcel->getActiveSheet()->setAutoFilter($objPHPExcel->getActiveSheet()->calculateWorksheetDimension()); 

// Rename worksheet 
$objPHPExcel->getActiveSheet()->setTitle('SimpleTest'); 

// Add a second sheet, but infront of the existing sheet 
//$myWorkSheet = new PHPExcel_Worksheet($objPHPExcel,'New Worksheet'); 
//$objPHPExcel->addSheet($myWorkSheet,0); 


// Set active sheet index to the first sheet, so Excel opens this as the first sheet 
$objPHPExcel->setActiveSheetIndex(0); 


// Redirect output to a client’s web browser (Excel2007) 
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); 
header('Content-Disposition: attachment;filename="ExportAllToExcelTest.xlsx"'); 
header('Cache-Control: max-age=0'); 
// If you're serving to IE 9, then the following may be needed 
header('Cache-Control: max-age=1'); 

// If you're serving to IE over SSL, then the following may be needed 
header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past 
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified 
header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1 
header ('Pragma: public'); // HTTP/1.0 

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007'); 
///$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel); 
ob_clean(); 
$objWriter->save('php://output'); 
?> 

답변

0

나는이 문제를 해결했다.

$.fn.dataTable.ext.buttons.export = 
{ 
    className: 'buttons-alert', 
    id: 'ExportButton', 
    text: "Export All To Excel", 
    action: function (e, dt, node, config) 
    { 
     window.location.href = './ServerSide.php?ExportToExcel=Yes'; 
    } 
}; 

난 그냥 하나 $_GET를 사용하여 시작하는 내 ServerSide.php 파일, 브라우저에 대한 데이터를 얻을 같은 파일이 전송 :이 이제 버튼입니다. 거기에 내가 지금 확인하고 필터링을 유지하기 위해 내 KeepPost.php에게 파일을 사용하고 사용자가 보고서에 배치했다고 정렬 : ServerSide.php 나는 $_GET['ExportToExcel']를 확인

<?php 

    if(isset($_POST['draw'])) 
     { 
      include 'DBConn.php'; 
      //echo "Here"; 
      //print_r($_POST); 
      $KeepPost = $_POST;  
      $KeepPost['length'] = -1; 
      $PostKept = serialize($KeepPost); 
      $TSQL = "UPDATE PostKept set Value = '" .$PostKept. "'"; 
      $sth = $conn->prepare($TSQL); 
      //print_r($sth); 
      $sth->execute(); 
     } 
?> 

다음 :

if (isset($_GET['ExportToExcel']) && $_GET['ExportToExcel'] == 'Yes') 
{ 
    $GetSQL = "Select Value from PostKept"; 
    $KeepResult = $conn->query($GetSQL); 
    $KeepResults = $KeepResult->fetchALL(PDO::FETCH_ASSOC); 

    //print_r($KeepResults); 
    error_log(date("Y/m/d h:i:sa")." KeepResults: " .$KeepResults[0]['Value']. "\n",3,"C:\Temp\LogPHP.txt"); 
    //findSerializeError($_COOKIE['KeepPost']); 
    //print_r($_COOKIE); 
    $request = unserialize($KeepResults[0]['Value']); 
    //echo "<br>Request: "; print_r($request); 

    $DataReturn = json_encode(FilterSort::complex($request,$sqlConnect,$table,$primaryKey,$ColumnHeader,1)); 
    //echo "DataReturn:<br>"; print_r($DataReturn); 
    require './ExportAllToExcel.php'; 
} 

이 다음 ExportAllToExcel.php 파일에 대한 올바른 데이터를 전송하고 사용자가 원하는 데이터를 내 보냅니다.