PHPExcel 将零输出为空白单元格

2022-08-30 16:02:36

我正在使用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

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

尝试更改:

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

...自。。。

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

答案 2

推荐