Hardcoding headers to excel file using PHP while dynamically querying SQL

折月煮酒 提交于 2019-12-23 03:22:26

问题


I have this PHPExcel code:

/** Error reporting */
error_reporting(E_ALL);
date_default_timezone_set('Europe/London');

/** Include PHPExcel */
require_once '../Classes/PHPExcel.php';
    $objPHPExcel = new PHPExcel();
    //$objPHPExcel->setActiveSheetIndex(0)
               // ->setCellValue('A1', 'Hello')
               // ->setCellValue('A2', 'world!')

$row = 2; 
while($row_data = mysql_fetch_assoc($result)) {
    $col = 1;
    foreach($row_data as $key=>$value) {
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $value);
$col++;
    }
        $row++;
    }

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

// 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 (Excel5)
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="Output.xls"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
exit;

Basically I am dynamically querying the database and placing it into an excel file.

I just want to hardcode in a few headers. So for A1 I'd like to hardcode in "Hello" and A2: "World!" while querying the database and putting the data starting in Column B


回答1:


$objPHPExcel = new PHPExcel();
$objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', 'Hello')
            ->setCellValue('A2', 'world!');

$col = 1; 
while($row_data = mysql_fetch_assoc($result)) {
    $row = 1;
    foreach($row_data as $value) {
        $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $value);
        $row++;
    }
    $col++;
}

Note that Excel5 has a limit of 256 columns, so if you have more than 255 data records the additional columns will de dropped from the saved workbook if you're saving to that format.



来源:https://stackoverflow.com/questions/13166502/hardcoding-headers-to-excel-file-using-php-while-dynamically-querying-sql

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