2016-12-04 169 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 
      } 

     } 
} 

要求

這正好給結果