1

我有这个PHPExcel代码:

/** 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;

基本上我是在动态查询数据库并将其放入一个 excel 文件中。

我只想在一些标题中硬编码。所以对于 A1,我想在“Hello”和 A2 中硬编码:“World!” 查询数据库并将数据从 B 列开始

4

1 回答 1

0
$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++;
}

请注意,Excel5 有 256 列的限制,因此如果您有超过 255 条数据记录,如果您要保存为该格式,则额外的列将从保存的工作簿中删除。

于 2012-10-31T19:59:28.883 回答