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

2025-02-17 14:16 By "Powerless" 1597 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

  • HTTP头中隐藏PHP版本号
    Posted on 2021-01-11 16:38
  • Composer 异常 [ErrorException]
    Posted on 2019-11-25 17:55
  • TCP协议的特性
    Posted on 2019-04-26 16:46
  • 能创建多少个 TCP 连接?
    Posted on 2021-08-02 16:00
  • PHP练习-移动数组内的0到最后并保持其他元素顺序不变
    Posted on 2020-08-14 20:32
  • Mysql联合索引的最左前缀匹配原则
    Posted on 2018-08-25 15:00
  • PHP没你想的那么差
    Posted on 2021-12-17 15:40
  • 快速了解Kafka
    Posted on 2021-03-25 14:20