我遇到了这个问题。 因为这个问题得到了很多意见,所以我想扔两分钱。
设置单元格值
而不是分别设置每个单元格的值,请使用fromArray()方法。 从维基采取和修改。
$arrayData = array( array(NULL, 2010, 2011, 2012), array('Q1', 12, 15, 21), array('Q2', 56, 73, 86), array('Q3', 52, 61, 69), array('Q4', 30, 32, 0), ); $as = $objPHPExcel->getActiveSheet(); $as->fromArray( $arrayData, // The data to set NULL, // Array values with this value will not be set 'C3' // Top left coordinate of the worksheet range where // we want to set these values (default is A1) );
造型细胞
静态的
对范围应用样式也比单独设置样式(注意模式)要快。
$default_style = array( 'font' => array( 'name' => 'Verdana', 'color' => array('rgb' => '000000'), 'size' => 11 ), 'alignment' => array( 'horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER, 'vertical' => \PHPExcel_Style_Alignment::VERTICAL_CENTER ), 'borders' => array( 'allborders' => array( 'style' => \PHPExcel_Style_Border::BORDER_THIN, 'color' => array('rgb' => 'AAAAAA') ) ) ); // Apply default style to whole sheet $as->getDefaultStyle()->applyFromArray($default_style); $titles = array( 'Name', 'Number', 'Address', 'Telephone' ); $title_style = array( 'font' => array( 'bold' => true ), 'fill' => array( 'type' => \PHPExcel_Style_Fill::FILL_SOLID, 'startcolor' => array('rgb' => '5CACEE') ), 'alignment' => array( 'wrap' => true ) ); $as->fromArray($titles, null, 'A1'); // Add titles $last_col = $as->getHighestColumn(); // Get last column, as a letter // Apply title style to titles $as->getStyle('A1:'.$last_col.'1')->applyFromArray($title_style);
dynamic
我使用PHPExcel检查数据库中当前数据的电子表格中给出的数据。 由于每个单元格都是单独检查的,因此我将样式放在一个数组中(null表示没有样式),并使用下面的循环来获取应用样式的单元格区域。
/* * $row is previously set in a loop iterating through each * row from the DB, which is equal to a spreadsheet row. * $styles = array(0 => 'error', 1 => 'error', 2 => null, 3 => 'changed', ...); */ $start = $end = $style = null; foreach ($styles as $col => $s) { if (!$style && !$s) continue; if ($style === $s) { $end = $col; } else { if ($style) { $array = null; switch ($style) { case 'changed': $array = $this->changed_style; break; case 'error': $array = $this->error_style; break; case 'ignored': $array = $this->ignored_style; break; } if ($array) { $start = \PHPExcel_Cell::stringFromColumnIndex($start); $end = \PHPExcel_Cell::stringFromColumnIndex($end); $as->getStyle($start.$row.':'.$end.$row)->applyFromArray($array); } } $start = $end = $col; $style = $s; } }