2016-12-04 136 views
1

我想完整阅读Excel表格,并使用AJAX将每行发送到另一页面进行处理。因此,我已用下面的代码为excel表数据转换成JSON阵列(在库中提供的参考PHPExcel示例):使用PHPExcel阅读包含合并单元格的Excel表格

<?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)

merged cells excel sheet example

这里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' 

回答

3

参照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 
      } 

     } 
} 

要求

这正好给结果