Export and download query results to Excel file in PHP from oracle

只愿长相守 提交于 2019-12-25 14:25:39

问题


// Export results
require_once('PHPExcel.php');
$query = "SELECT DISTINCT TITLE, PID, TYPE, SUM(DAYCOUNT) AS tot, ROUND(SUM(DAYCOUNT)/( SELECT SUM(DAYCOUNT) FROM REPORT_LIST_VIEW), 4) AS per FROM REPORT_LIST_VIEW WHERE DAYCOUNT > '0' GROUP BY TITLE, PID, TYPE ORDER BY tot DESC";
if ($result = db_query($query)) {
    // Create a new PHPExcel object
    $objPHPExcel = new PHPExcel();
    $objPHPExcel->getActiveSheet()->setTitle('List of Cities');
    // Loop through the result set
    $rowNumber = 1;
    while ($row = $result->fetchAssoc()) {
        $objPHPExcel->getActiveSheet()->fromArray($row,NULL,'A'.$rowNumber++);
    }
    // Save as an Excel BIFF (xls) file
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    $objWriter->save('CityList.xls');
}

I tried this code in a PHP page to download query results from Oracle as an Excel file, but when I browse to the page, it is all blank and white like it is hung.

Any clues?


回答1:


Use this code that will download the excel file in local system Check folder permission as well

To download the excel file you need to set headers.So simply provide filename which will be the name of downloaded excel file.

// Export results
require_once('PHPExcel.php');
$query = "SELECT DISTINCT TITLE, PID, TYPE, SUM(DAYCOUNT) AS tot, ROUND(SUM(DAYCOUNT)/( SELECT SUM(DAYCOUNT) FROM REPORT_LIST_VIEW), 4) AS per FROM REPORT_LIST_VIEW WHERE DAYCOUNT > '0' GROUP BY TITLE, PID, TYPE ORDER BY tot DESC";
if ($result = db_query($query)) {
    // Create a new PHPExcel object
    $objPHPExcel = new PHPExcel();
    $objPHPExcel->getActiveSheet()->setTitle('List of Cities');
    // Loop through the result set
    $rowNumber = 1;
    while ($row = $result->fetchAssoc()) {
        $objPHPExcel->getActiveSheet()->fromArray($row,NULL,'A'.$rowNumber++);
    }



// Redirect output to a client’s web browser (Excel5)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="CityList.xls"');
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: Fri, 11 Sep 2015 05:00:00 GMT'); // Date
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, 'Excel5');
$objWriter->save('php://output');
exit;
}


来源:https://stackoverflow.com/questions/32516841/export-and-download-query-results-to-excel-file-in-php-from-oracle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!