如何使PHPEXcel从数据库中添加其他字段

时间:2012-09-28 14:13:34

标签: php phpexcel

我曾尝试使用phpexcel.codeplex.com创建一个PHPExcel类的spreedsheet,但我遇到了一个情况,无法弄清楚出了什么问题。

我在数据库中有3个字段要插入spreedsheet'名称,'price','stock'。

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

这是我正在处理的代码:

$ sql =“SELECT name,price,stock FROM products”;

$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;

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

提前致谢!

1 个答案:

答案 0 :(得分:2)

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

列参数应为数值:0 =列A,1 =列B等。 你正在使用一个字符串,它将通过类型变为数字0,所以所有内容都被写入第一个(0)列,覆盖已经存在的任何内容....我很惊讶你不是简单地获取值最后(股票)专栏