簡體   English   中英

通過發布將數據發送到url以使用javascript導出到excel

[英]Sending data to url through post to export to excel using javascript

我有一個報告網站,在上面使用了DataTables Server Side Processing。 一切工作正常,除了我需要能夠導出整個數據集,而不僅僅是導出屏幕上顯示的部分。 我的報告包含10,000+行和65+列,因此在頁面上顯示整個報告是不可能的(將花費5分鍾以上,然后超時)。 我認為我已經很接近答案了,但在其余過程中需要幫助。 這是我得到的:

我正在收集需要發送到使用PHPExcel庫導出Excel文件的文件中的數據。

當我導航到文件( 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');
?>

我已經解決了這個問題。 現在是按鈕:

$.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文件保持用戶已放置在報告上的過濾和排序:

<?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();
        }
?>

然后在ServerSide.php中,我檢查$_GET['ExportToExcel']

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文件,並導出用戶所需的數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM