繁体   English   中英

使用PHPExcel读取包含合并单元格的Excel工作表

[英]Read excel sheet containing merged cells using PHPExcel

我想完整地阅读Excel工作表,并使用AJAX将每一行发送到另一页进行处理。 因此,我使用以下代码将excel工作表数据转换为JSON数组(库中提供的参考PHPExcel示例):

<?php
error_reporting(E_ALL);
set_time_limit(0);

date_default_timezone_set('Asia/Kolkata');
set_include_path(get_include_path() . PATH_SEPARATOR . 'PHPExcel-1.8/Classes/');
require_once 'PHPExcel/IOFactory.php';

$inputFileType = PHPExcel_IOFactory::identify($fileLocation);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objReader->setLoadSheetsOnly("SHEETNAME");
$objPHPExcel = $objReader->load($fileLocation);

$data = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
?>

这里$filelocation是上载文件的位置,将使用AJAX将行分别发送到另一页时读取该文件。 我在javascript中使用$data作为

DataToBeUploaded=<?php echo json_encode($data);?>;

但是excel工作表包含一些合并的单元格,因此PHPExcel无法读取这些合并的单元格中的值。 因此,这些单元格中的值被读取为NULL。

有没有一种方法可以将合并单元格的左上单元格值用于所有后续单元格? (实际上,在我的情况下,单元仅垂直合并)

例如。 我有(假设行从1编号,列从A编号)

合并单元格Excel工作表示例

在这里,PHPExcel将其读取为:

data[1][A]='abc'
$data[1][B]='123'

$data[2][A]=''
$data[2][B]='456'

$data[3][A]=''
$data[3][B]='789'

我希望代码片段产生以下值:

data[1][A]='abc'
$data[1][B]='123'

$data[2][A]='abc'
$data[2][B]='456'

$data[3][A]='abc'
$data[3][B]='789'

参考https://github.com/PHPOffice/PHPExcel/issues/643

我写了以下代码片段:

$referenceRow=array();
for ( $row = 2; $row <= $noOfBooks; $row++ ){
     for ( $col = 0; $col < 7; $col++ ){
         if (!$objPHPExcel->getActiveSheet()->getCellByColumnAndRow( $col, $row )->isInMergeRange() || $objPHPExcel->getActiveSheet()->getCellByColumnAndRow( $col, $row )->isMergeRangeValueCell()) {
             // Cell is not merged cell
             $data[$row][$col] = $objPHPExcel->getActiveSheet()->getCellByColumnAndRow( $col, $row )->getCalculatedValue();

             $referenceRow[$col]=$data[$row][$col];  
             //This will store the value of cell in $referenceRow so that if the next row is merged then it will use this value for the attribute
          } else {
             // Cell is part of a merge-range
             $data[$row][$col]=$referenceRow[$col];  
             //The value stored for this column in $referenceRow in one of the previous iterations is the value of the merged cell
          }

      }
 }

这将完全按照要求提供结果

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM