【PHP】使用phpoffice/phpspreadsheet导入导出数据

时间:2019-11-27
本文章向大家介绍【PHP】使用phpoffice/phpspreadsheet导入导出数据,主要包括【PHP】使用phpoffice/phpspreadsheet导入导出数据使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

当你在使用phpoffice/phpexcel 类库时候。composer 会给你提示一句话

Package phpoffice/phpexcel is abandoned, you should avoid using it. Use phpoffice/phpspreadsheet instead

phpexcel 已被废弃,建议我们用phpspreadsheet,

包地址:

https://packagist.org/packages/phpoffice/phpspreadsheet

composer:

composer require phpoffice/phpspreadsheet

使用

引入

use \PhpOffice\PhpSpreadsheet\Spreadsheet;
use \PhpOffice\PhpSpreadsheet\IOFactory;
//use \PHPExcel_Style_NumberFormat;    //设置列的格式==>>设置文本格式

导出:

 //execl模板下载
    public function template_download()
    {
        $newExcel = new Spreadsheet();  //创建一个新的excel文档
        $objSheet = $newExcel->getActiveSheet();  //获取当前操作sheet的对象
        $objSheet->setTitle('导入模板');  //设置当前sheet的标题

        //设置宽度为true,不然太窄了
        $newExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true);

        //设置第一栏的标题
        $objSheet->setCellValue('A1', '用户id')
            ->setCellValue('B1', '昵称')
            ->setCellValue('C1', '手机号');

        //默认数据
        $explame_data_list = array(
            array(
                'user_id' => '1',
                'nickname' => '小明',
                'phone' => '15012345678',
            ),
        );

        //第二行起,每一行的值,setCellValueExplicit是用来导出文本格式的。
        //->setCellValueExplicit('C' . $k, $val['admin_password']PHPExcel_Cell_DataType::TYPE_STRING),可以用来导出数字不变格式
        $baseRow = 2; //数据从N-1行开始往下输出 这里是避免头信息被覆盖
        foreach ($explame_data_list as $k => $val) {
            $i = $k + $baseRow;
            $objSheet->setCellValue('A' . $i, $val['user_id'])
                ->setCellValue('B' . $i, $val['nickname'])
                ->setCellValue('C' . $i, $val['phone']);
        }

        $this->downloadExcel($newExcel, '会员批量导入模板', 'Xls');
    }

    //公共文件,用来传入xls并下载
    private function downloadExcel($newExcel, $filename, $format)
    {
        // $format只能为 Xlsx 或 Xls
        if ($format == 'Xlsx') {
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        } elseif ($format == 'Xls') {
            header('Content-Type: application/vnd.ms-excel');
        }

        header("Content-Disposition: attachment;filename="
            . $filename . date('Y-m-d') . '.' . strtolower($format));
        header('Cache-Control: max-age=0');
        $objWriter = IOFactory::createWriter($newExcel, $format);

        $objWriter->save('php://output');

        //通过php保存在本地的时候需要用到
        //$objWriter->save($dir.'/demo.xlsx');

        //以下为需要用到IE时候设置
        // If you're serving to IE 9, then the following may be needed
        //header('Cache-Control: max-age=1');
        // If you're serving to IE over SSL, then the following may be needed
        //header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        //header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        //header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        //header('Pragma: public'); // HTTP/1.0
        exit;
    }

导入

 //会员批量导入提交
    public function import_batch_send()
    {
        header("content-type:text/html;charset=utf-8");
        //上传excel文件
        $file = request()->file('file');
        //将文件保存到public/uploads目录下面
        $info = $file->validate(['size' => 1048576, 'ext' => 'xls'])->move('./uploads');
        if ($info) {
            //获取上传到后台的文件名
            $fileName = $info->getSaveName();
            //获取文件路径
            $filePath = Env::get('root_path') . 'public' . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . $fileName;
            //获取文件后缀
            $suffix = $info->getExtension();
            // 有Xls和Xlsx格式两种
            $reader = IOFactory::createReader('Xls');
        } else {
            return json(['status' => '1', 'message' => '文件过大或格式不正确导致上传失败-_-!']);
        }
        //载入excel文件
        $excel = $reader->load($filePath, $encode = 'utf-8');
        //读取第一张表
        $sheet = $excel->getSheet(0);
        //获取总行数
        $row_num = $sheet->getHighestRow();
        //获取总列数
        $col_num = $sheet->getHighestColumn();

        $import_data = []; //数组形式获取表格数据
        for ($i = 2; $i <= $row_num; $i++) {
            $import_data[$i]['nickname']   = $excel->getActiveSheet()->getCell("A" . $i)->getValue();
            $import_data[$i]['phone']    = $excel->getActiveSheet()->getCell("C" . $i)->getValue();
        }

        if (empty($import_data)) {
            return json(['status' => '1', 'message' => '数据解析失败']);
        }

        //校验手机号是否重复
        $phone_array = array_column($import_data, 'phone');
        $phone_ids = implode(',', $phone_array);
        $result_phone = db('user')
            ->field('phone')
            ->where('phone', 'in', $phone_ids)
            ->select();
        if (!empty($result_phone)) {
            $result_phone_array = array_column($result_phone, 'phone');
            $result_phone_ids = implode(',', $result_phone_array);
            return json(['status' => '3', 'message' => '数据重复', 'result' => $result_phone_ids]);
        }

        //将数据保存到数据库
        $res = db('user')->insertAll($import_data);
        if ($res) {
            return json(['status' => '2', 'message' => '导入成功']);
        } else {
            return json(['status' => '1', 'message' => '提交失败,请刷新重试']);
        }
    }

原文地址:https://www.cnblogs.com/richerdyoung/p/11942431.html