0

我试图从 phpexcel.codeplex.com 创建一个带有 PHPExcel 类的电子表格,但我遇到了一个情况,无法弄清楚出了什么问题。

我有 3 个来自数据库的字段要插入到电子表格“名称”、“价格”、“库存”中。

问题是我只得到产品名称,这是表中的第一个字段。

这是我正在处理的代码:

$sql = "从产品中选择名称、价格、库存";

$objPHPExcel = new PHPExcel();

$res = $con->query( $sql );

// First row
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow( 'name', 1, 'Name' );
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow( 'price', 1, 'Price' );
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow( 'stock', 1, 'Stock' );

// Other rows
$i = 2;
while( $row = $res->fetch( PDO::FETCH_ASSOC ) ) {
    foreach( $row as $col => $data ) {
        $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow( $col, $i, $data );
    }
    $i++;
}

// Redirect output to a client web browser (Excel5)
header( 'Content-Type: application/vnd.ms-excel' );
header( 'Content-Disposition: attachment;filename="report.xls"' );
header( 'Cache-Control: max-age=0' );

$objWriter = PHPExcel_IOFactory::createWriter( $objPHPExcel, 'Excel5' );
$objWriter->save( 'php://output' );
exit;

我看不到我错过了什么...

提前致谢!

4

1 回答 1

2
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow( 'name', 1, 'Name' ); 

column 参数应该是一个数值:0 = A 列,1 = B 列,等等。您使用的是一个字符串,它的类型将被转换为数字 0,因此所有内容都被写入第一 (0) 列,覆盖已经存在的任何内容....令我惊讶的是,您不仅仅获得了最后一个(股票)列的值

于 2012-09-28T14:18:11.400 回答