PHPExel输出零作为空白单元格

gijlo24d  于 2023-03-07  发布在  PHP
关注(0)|答案(2)|浏览(267)

我正在使用PHPExel构建一个WordPress插件来导出学生出勤报告。到目前为止,我能够成功地获取学生数据(包括出勤)的数组,并将其转换为电子表格并下载。不幸的是,有一个奇怪的bug:当一个学生没有参加任何活动时,电子表格上的单元格就会显示为空白,而不是显示为零。我希望它实际上显示为零,但我找不到这样做的方法。下面是我的脚本:

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()函数填充电子表格,我应该做些什么来使这些零正确显示?

nle07wnf

nle07wnf1#

我认为您是松散类型比较的受害者-您将null指定为fromArray()的第二个参数,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 );
vxbzzdmp

vxbzzdmp2#

年2023,你必须使用PhpSpreadSheets,这是Phpexcel的演变.
为了避免显示空白而不是显示零,您可以指定特定列的文本格式:
在本例中,我指出从B到D列具有FORMAT_TEXT getStyle('B:D')

// you should include this use.
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;

$spreadsheet->getActiveSheet()->getStyle('B:D')->getNumberFormat()->setFormatCode(PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_TEXT);

相关问题