PHP读取EXCEL报错:Xlsx::getArrayItem()节点不再存在

2025-02-17 14:16 By "Powerless" 1646 0 0

修复方式:【在载入文件前设置只读】

原因:不同版本和厂商的excel文件可能导致一些未知错误。

$reader->setReadDataOnly(true);

完整示例:

protected function getExcelData($request, $start = 3)
{
    $file = $request['file'] ?? [];
    if (!$file) $this->throw('请上传文件');
    $type = IOFactory::identify($file['tmp_name']);                                 //使用自动阅读器解析识别文件类型。
    $reader = IOFactory::createReader($type);                                       //创建读取器
    $reader->setReadDataOnly(true);                                          //设置只读
    $spreadsheet = $reader->load($file['tmp_name']);                                //从文件中加载
    $activesheet = $spreadsheet->getActiveSheet();                                  //获取活动工作表
    $highest = $activesheet->getHighestRowAndColumn();                              //获取具有单元格记录的最高工作表列和最高行。
    $highestColumnIndex = Coordinate::columnIndexFromString($highest['column']);    //字符串中的列索引
    $data = [];
    for ($col = 1; $col <= $highestColumnIndex; $col++) {
        $mark = Coordinate::stringFromColumnIndex($col);                            //来自列索引的字符串
        for ($row = 1; $row <= $highest['row']; $row++) {
            $key = $mark . $row;
            $value = $activesheet->getCell($key)->getFormattedValue();              //使用格式获取单元格值
            $data[$row][$mark] = $value;
        }
    }
    foreach ($data as $key => $item) {
        if (!array_filter($item)) unset($data[$key]);
    }
    if (count($data) < $start) $this->throw('请填写表格');
    return $data;
}

评 论

View in WeChat

Others Discussion

  • Redis各种数据类型的使用场景举例分析【三】
    Posted on 2018-11-22 17:00
  • 投票通过,PHP 8 确认引入 Union Types 2.0
    Posted on 2019-11-18 22:22
  • PHP设计模式 - 委托模式
    Posted on 2019-04-25 16:15
  • BASE原则
    Posted on 2020-12-17 16:42
  • PHP扩展安装
    Posted on 2019-06-24 11:28
  • 程序员年中考试题-段子版
    Posted on 2021-06-23 15:57
  • 一些常见的基础概念
    Posted on 2018-11-28 19:10
  • HTTP和HTTPS的区别
    Posted on 2020-08-10 23:00