excel导出到php数组的方法-PhpSpreadsheet库

网站技术 ayflying 369℃ 评论

PhpSpreadsheet由来:

phpexcel 由于版本陈旧性能低下 官方放弃维护

转而开发PhpSpreadsheet 用了最新得psr标准因而 对php版本不向下兼容 需要注意!。


PhpSpreadsheet是一个用纯PHP编写的库,提供了一组类,使您可以读取和写入不同的电子表格文件格式

PhpSpreadsheet提供了丰富的API接口,可以设置诸多单元格以及文档属性,包括样式、图片、日期、函数等等诸多应用,总之你想要什么样的Excel表格,PhpSpreadsheet都能做到


使用 PhpSpreadsheet 开发的PHP要求 7.1或更高版本

PhpSpreadsheet 支持链式操作


老方法,首先使用composer安装库

composer require phpoffice/phpspreadsheet

然后使用以下方法导出到数组

/**
 * 表格转数组
 * @param string $file  excel文件位置
 * @return array
 */
public function excel2array(string $file): array
{
    if (!is_file($file)) {
        return [];
    }
    //获取所有标签
    $Sheets = \PhpOffice\PhpSpreadsheet\IOFactory::load($file)->getAllSheets() ?? [];
    $list = [];
    foreach ($Sheets as $Sheet) {
        //获取工作表页签名称
        $title = $Sheet->getTitle();
        //所有数据转字段
        $res = $Sheet->getCellCollection()->getParent()->toArray();
        $list[$title] = $res;
    }
    return $list;
}


转载请注明:七彩悠悠博客 | 心悠悠 情悠悠 » excel导出到php数组的方法-PhpSpreadsheet库

高效,专业,悠悠博客

联系我们