phpexcel:从功能设置样式

时间:2016-11-18 09:53:04

标签: php phpexcel

如何从函数中设置所有单元格样式/选项?

此代码对我不起作用:

function setStyleTest() {
    global $objPHPExcel, $cell;
    $objPHPExcel->setActiveSheetIndex(0)->getStyle( $cell )->getFont()->setSize( 10 );
    $objPHPExcel->setActiveSheetIndex(0)->getStyle( $cell )->getAlignment()->setWrapText(true);
}

$cell = "A1";
$objPHPExcel->setActiveSheetIndex(0)->setCellValue( $cell, 'Some content' );

setStyleTest();

但这有效:

$cell = "A1";
$objPHPExcel->setActiveSheetIndex(0)->setCellValue( $cell, 'Some content' );
$objPHPExcel->setActiveSheetIndex(0)->getStyle( $cell )->getFont()->setSize( 10 );
$objPHPExcel->setActiveSheetIndex(0)->getStyle( $cell )->getAlignment()->setWrapText(true);

是的,我对课程知之甚少=)谢谢!

1 个答案:

答案 0 :(得分:0)

你们两个代码示例都有效,问题在于变量$ cell。它必须是与电子表格中的单元格对应的字符串。例如,要访问单元格A1,请更改$ cell,如下所示:

$cell = "A1";

现在你的函数setStyleTest()每次都会设置相同的静态单元格,为了动态使用它我会推荐这个:

$cell = "A1";
$objPHPExcel->setActiveSheetIndex(0)->setCellValue( $cell, 'Some content' );
$objPHPExcel->setActiveSheetIndex(0)->getStyle( $cell )->getFont()->setSize( 10 );
$objPHPExcel->setActiveSheetIndex(0)->getStyle( $cell )->getAlignment()->setWrapText(true); 

function setStyleTest($incomingCell) {
  global $objPHPExcel;
  $objPHPExcel->setActiveSheetIndex(0)->getStyle( $incomingCell )->getFont()->setSize( 10 );
  $objPHPExcel->setActiveSheetIndex(0)->getStyle( $incomingCell )->getAlignment()->setWrapText(true);
  //I added BOLD to make this easier to see the difference
  $objPHPExcel->getActiveSheet()->getStyle($incomingCell)->getFont()->setBold(true);
}

$cell2 = "B1";
$objPHPExcel->setActiveSheetIndex(0)->setCellValue( $cell2, 'Some content2' );

setStyleTest($cell2);