问题
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