【问题标题】:Read excel sheet containing merged cells using PHPExcel使用 PHPExcel 读取包含合并单元格的 excel 表
【发布时间】:2017-04-19 00:20:19
【问题描述】:

我想完整阅读 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 开始)

这里 PHPExcel 将其读取为:

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

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

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

我希望 sn-p 产生这些值:

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

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

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

【问题讨论】:

    标签: php excel phpexcel cells


    【解决方案1】:

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

    我写了以下sn-p:

    $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
              }
    
          }
     }
    

    这将给出完全符合要求的结果

    【讨论】:

      猜你喜欢
      • 2015-10-02
      • 2014-05-21
      • 2021-01-17
      • 2021-01-09
      • 1970-01-01
      • 2011-10-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多