使用PHPExcel阅读包含合并单元格的Excel表格
我想完整地阅读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。
有没有一种方法可以将所有后续单元格的合并单元格的左上angular单元格值使用? (其实在我的情况下,细胞只能垂直合并)
例如。 我有(假设行从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'
我想要的片段导致这些值:
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 } } }
这将根据需要给出结果