PHP-PHPExcel数组范围忽略空列

时间:2019-12-17 07:39:26

标签: php laravel phpexcel phpspreadsheet

我在Excel工作表的下面,我要在其中将范围A1:D4放入PHP数组。

enter image description here

为此,我正在使用PHPExcel,如下所示。我有一个简单的Excel类:

Excel.php

public function __construct($file)
{
     if ($file instanceof \SplFileInfo) {
         $filename = $file->getRealPath();
     } else {
         $filename = $file;
     }

     $this->objPHPExcel = \PhpOffice\PhpSpreadsheet\IOFactory::load($filename);
     $this->objPHPExcel->setActiveSheetIndex(0);
}

然后我有一个简单的函数,可以使用rangeToArray()函数来获取范围:

public function getRange($range)
{
    $spreadsheet = $this->objPHPExcel;
    return $spreadsheet->rangeToArray($range,'  ', true, true, true);

}

$excel = new ExcelManipulator(storage_path() . '/app/temp_files/myfile.xlsx');
$array = $excel->getRange($range);

return response()->json(['result' => $array], 200);

现在的问题是上述函数“切换”了列。看到下面的输出:

[
  '1': [
     "A": "  ", 
     "B": "  ",
     "C": "  ",
     "D": "  "
  ],
  '2': [
     "A": "Company", 
     "B": "Acme Inc",
     "C": "  ",
     "D": "  "
  ],
  '3': [
     "A": "Address", 
     "B": "New York",
     "C": "  ",
     "D": "  "
  ],
  '4': [
     "A": "  ", 
     "B": "  ",
     "C": "  ",
     "D": "  "
  ]
]

正如您在行23的数组中看到的那样,公司地址文本已从{{1} },而它们应该以{{1​​}}

开始

2 个答案:

答案 0 :(得分:3)

您可以尝试

function getRange($range, $inputFileName)
{
    $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($inputFilename);
    return $spreadsheet->getActiveSheet()->rangeToArray($range," ", true, true, true);

}
$inputFilename = storage_path() . '/app/temp_files/myfile.xlsx';
$array = getRange($range, $inputFilename);

答案 1 :(得分:1)

使用php 7.2.26和phpoffice / phpspreadsheet 1.10.1对我来说效果很好。我创建了一个具有与您相同的单元格值的xlsx文件。

$excel = new Excel('file.xlsx');
$range = 'A1:D4';
$array = $excel->getRange($range);

var_dump($array);

class Excel
{
  private $objPHPExcel;

  public function __construct($file)
  {
     if ($file instanceof \SplFileInfo) {
         $filename = $file->getRealPath();
     } else {
         $filename = $file;
     }

     $this->objPHPExcel = \PhpOffice\PhpSpreadsheet\IOFactory::load($filename);
     $this->objPHPExcel->setActiveSheetIndex(0);
  }

  public function getRange($range)
  {
    $spreadsheet = $this->objPHPExcel->getActiveSheet();
    return $spreadsheet->rangeToArray($range,'  ', true, true, true);
  }
}

这是输出:

array(4) {
  [1] =>
  array(4) {
    'A' =>
    string(2) "  "
    'B' =>
    string(2) "  "
    'C' =>
    string(2) "  "
    'D' =>
    string(2) "  "
  }
  [2] =>
  array(4) {
    'A' =>
    string(2) "  "
    'B' =>
    string(7) "Company"
    'C' =>
    string(8) "Acme Inc"
    'D' =>
    string(2) "  "
  }
  [3] =>
  array(4) {
    'A' =>
    string(2) "  "
    'B' =>
    string(7) "Address"
    'C' =>
    string(8) "New York"
    'D' =>
    string(2) "  "
  }
  [4] =>
  array(4) {
    'A' =>
    string(2) "  "
    'B' =>
    string(2) "  "
    'C' =>
    string(2) "  "
    'D' =>
    string(2) "  "
  }
}