PhpSpreadsheet 实现excel 导入数据

这篇博客介绍了如何利用PhpSpreadsheet库通过composer安装,并详细讲解了文件上传及读取Excel内容为数组的方法,为数据处理提供便利。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、composer

composer require phpoffice/phpspreadsheet

2、文件传入方法

public function talentImport(string $file_name='excelFile')
{
    $file = \Illuminate\Support\Facades\Request::file($file_name);

    if ($file) {

        if(!$file->isValid()) {
            return '文件有误';
        }

        if (!in_array($file->getClientOriginalExtension(), ['xls', 'xlsx'])) {
            return '只允许上传xlsxlsx格式的文件';
        }

        $excel_file_path = $file->getRealPath();

        if (!is_uploaded_file($excel_file_path)) {
            return '非法上传';
        }

        $sheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($excel_file_path)->getActiveSheet();


        $res = array();

        foreach ($sheet->getRowIterator(2) as $row) {

            $tmp = array();

            foreach ($row->getCellIterator() as $cell) {

                $tmp[] = $cell->getFormattedValue();

            }

            $res[$row->getRowIndex()] = $tmp;

        }

        if (empty($res)) {
            return '无法读取文件内容或文件内容为空';
        }

        return $res;
    }

    return '请上传excel文件';
}

3、对文件内容的数组进行操作

   

foreach ($res as $row) {
    
    验证数据正确性
    
    存入insert数组

}

    insert($array)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值