PHPExcel输出零作为空白单元格

时间:2012-03-14 14:58:55

标签: php phpexcel

我正在使用PHPExcel构建一个WordPress插件来导出学生出勤报告。到目前为止,我能够成功获取学生数据(包括出勤)并将其转换并下载为电子表格。不幸的是,有一个奇怪的错误:当学生参加零事件时,电子表格上的那个单元格是空白而不是显示零。我更喜欢它实际为零,但我找不到办法做到这一点。这是我的剧本:

error_reporting( E_ALL);
ini_set( 'include_path', ini_get( 'include_path' ).';../Classes/' );

include 'PHPExcel.php';
include 'PHPExcel/Writer/Excel2007.php';

$objPHPExcel = new PHPExcel();

$objPHPExcel->setActiveSheetIndex( 0 );
$objPHPExcel->getProperties()->setCreator( $user );
$objPHPExcel->getProperties()->setLastModifiedBy( $user );
$objPHPExcel->getProperties()->setTitle( $title );
$objPHPExcel->getProperties()->setSubject( $title );
$objPHPExcel->getProperties()->setDescription( $title );
$objPHPExcel->getActiveSheet()->fromArray( $data, null, 'A1' );
$objPHPExcel->getActiveSheet()->getStyle('A1:H1')->getFont()->setBold(true);

$columns = array( 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H' );

foreach ( $columns as $column ) {

    $objPHPExcel->getActiveSheet()->getColumnDimension($column)->setAutoSize(true);

} // End $columns foreach

$file_name = str_replace( ' ', '_', $title);

if ( $_POST['type'] == 'spreadsheet' ) {

header( 'Content-type: application/vnd.ms-excel' ); 
header( 'Content-Disposition: attachment; filename="' . $file_name . '.xls"' );

$objWriter = new PHPExcel_Writer_Excel2007( $objPHPExcel );
$objWriter->save( 'php://output' );

} 

$ data包含学生信息数组,其结构如下:

Array (
    [0] => Array (
        [0] => First Name
        [1] => Last Name
        [2] => BU ID
        [3] => Barcode
        [4] => Major
        [5] => Class
        [6] => Seminars
        [7] => Showcases
    )

    [1] => Array (
        [first_name] => Seth
        [last_name] => Abel
        [buid] => B00385307
        [barcode] => 100324707
        [student_major] => CMM
        [class] => MBU2100
        [seminar] => 0
        [showcase] => 1
    )

    [2] => Array (
        [first_name] => Zachary
        [last_name] => Abend
        [buid] => B00373103
        [barcode] => 100291996
        [student_major] => MBU
        [class] => MBU2100
        [seminar] => 0
        [showcase] => 1
    )
.
.
.
)

正如您所看到的是示例数据,这些学生每人都参加了1次展示,但没有参加过零研讨会。下载此电子表格并在Excel中打开时,1显示正常,但研讨会单元格为空白。由于我使用fromArray()函数来填充电子表格,我是否应该做些什么才能使这些零值正确显示?

1 个答案:

答案 0 :(得分:37)

我认为您是松散类型比较的受害者 - 您已将null指定为fromArray()的第二个参数,代表Value in source array that stands for blank cell。由于null == 0这意味着零将导致空白单元格,除非您将第四个参数设置为true

尝试更改:

$objPHPExcel->getActiveSheet()->fromArray( $data, null, 'A1' );

...到...

$objPHPExcel->getActiveSheet()->fromArray( $data, null, 'A1', true );