文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

fastadmin+phpspreadsheet实现导出和导入

2023-10-06 10:40

关注

在对应的index.html页面添加导航按钮,导出数据,直接在 添加对应方法,如果使用Ajax方法实现导出,会失败。

一、在对应的控制层,导入方法

use PhpOffice\PhpSpreadsheet\Reader\Xlsx;  //导入表使用use PhpOffice\PhpSpreadsheet\Reader\Xls;   //导入表使用use PhpOffice\PhpSpreadsheet\Reader\Csv;   //导入表使用use PhpOffice\PhpSpreadsheet\Spreadsheet;  //导出表使用use PhpOffice\PhpSpreadsheet\Cell\Coordinate; //导入表使用

 二、导出方法

public function downloadTemplate()    {        $spreadsheet = new Spreadsheet();        $sheet = $spreadsheet->getActiveSheet();               //设置表头        $sheet->setCellValue('A1', '考生ID');        $sheet->setCellValue('B1', '考生姓名');        $sheet->setCellValue('C1', '报名号');        $sheet->setCellValue('D1', '准考证号');        $sheet->setCellValue('E1', '笔试成绩');        $sheet->setCellValue('F1', '笔试成绩排名');        $sheet->setCellValue('G1', '面试成绩');        $sheet->setCellValue('H1', '面试成绩排名');            //改变此处设置的长度数值        $sheet->getColumnDimension('A')->setWidth(15);        $sheet->getColumnDimension('B')->setWidth(15);        $sheet->getColumnDimension('C')->setWidth(25);        $sheet->getColumnDimension('D')->setWidth(25);        $sheet->getColumnDimension('E')->setWidth(15);        $sheet->getColumnDimension('F')->setWidth(15);        $sheet->getColumnDimension('G')->setWidth(15);        $sheet->getColumnDimension('H')->setWidth(15);         //设置列水平居中        $sheet->getStyle('A')->getAlignment()                        ->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);        $sheet->getStyle('B')->getAlignment()                        ->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);        $sheet->getStyle('C')->getAlignment()                        ->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);        $sheet->getStyle('D')->getAlignment()                        ->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);        $sheet->getStyle('E')->getAlignment()                        ->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);        $sheet->getStyle('F')->getAlignment()                        ->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);        $sheet->getStyle('G')->getAlignment()                        ->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);        $sheet->getStyle('H')->getAlignment()                        ->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);        //输出表格        $sheet->setCellValueExplicitByColumnAndRow(1,2,'1',\PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);        $sheet->setCellValueExplicitByColumnAndRow(2,2,'张三',\PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);        $sheet->setCellValueExplicitByColumnAndRow(3,2,'20230330194812134',\PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);        $sheet->setCellValueExplicitByColumnAndRow(4,2,'202300100101',\PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);        $sheet->setCellValueExplicitByColumnAndRow(5,2,'95',\PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);        $sheet->setCellValueExplicitByColumnAndRow(6,2,'1',\PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);        $sheet->setCellValueExplicitByColumnAndRow(7,2,'92',\PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);        $sheet->setCellValueExplicitByColumnAndRow(8,2,'1',\PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);                $filename = '考生成绩导入模板'.date('ymdhis',time()).'.xlsx';        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');        header('Content-Disposition: attachment;filename="'.$filename.'"');        header('Cache-Control: max-age=0');        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');        $writer->save('php://output');        exit;    }

三、导入表格  实现更新数据操作

 public function import()    {        $file = $this->request->request('file');        if (!$file) {            // 参数%s不能为空            $this->error(__('Parameter %s can not be empty', 'file'));         }        $filePath = ROOT_PATH . DS . 'public' . DS . $file;        if (!is_file($filePath)) {            $this->error(__('No results were found'));        }        //实例化reader        $ext = pathinfo($filePath, PATHINFO_EXTENSION);               if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {            $this->error(__('Unknown data format'));        }        if ($ext === 'csv') {            $file = fopen($filePath, 'r');            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');            $fp = fopen($filePath, 'w');            $n = 0;            while ($line = fgets($file)) {                $line = rtrim($line, "\n\r\0");                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);                if ($encoding !== 'utf-8') {                    $line = mb_convert_encoding($line, 'utf-8', $encoding);                }                if ($n == 0 || preg_match('/^".*"$/', $line)) {                    fwrite($fp, $line . "\n");                } else {                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");                }                $n++;            }            fclose($file) || fclose($fp);        } elseif ($ext === 'xls') {            $reader = new Xls();        } else {            $reader = new Xlsx();        }        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';        $table = $this->model->getQuery()->getTable();        $database = \think\Config::get('database.database');        $fieldArr = [];        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);        foreach ($list as $k => $v) {            if ($importHeadType == 'comment') {                $v['COLUMN_COMMENT'] = explode(':', $v['COLUMN_COMMENT'])[0]; //字段备注有:时截取                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];            } else {                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];            }        }               //加载文件        $updataStudent = []; //批量更新数据               try {            if (!$PHPExcel = $reader->load($filePath)) {                $this->error(__('Unknown data format'));            }            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);            $fields = [];            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();                    $fields[] = $val;                }            }                        for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {                $values = [];                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();                    $values[] = is_null($val) ? '' : $val;                }                $row = [];                $temp = array_combine($fields, $values);                foreach ($temp as $k => $v) {                    if (isset($fieldArr[$k]) && $k !== '') {                        $row[$fieldArr[$k]] = $v;                    }                }                if ($row) {                    $updataStudent[] = $row;                }            }                } catch (Exception $exception) {            $this->error($exception->getMessage());        }        if (!$updataStudent) {            $this->error(__('No rows were meiy'));        }        $result = false;        Db::startTrans();        try {            $student = [];            foreach($updataStudent as $item){                $student = [                    'id' => (int)$item['id'],                    // 'examinee_name' => $item['examinee_name'],                     // 'exam_score_sort' => $item['signup_number'],                    // 'admission_ticket' => $item['admission_ticket'],                    'exam_score' => $item['exam_score'],   //笔试成绩                    'exam_score_sort' => $item['exam_score_sort'],   //                    'interview_score' => $item['interview_score'],   //面试成绩                    'interview_score_sort' => $item['interview_score_sort'],                  ];   $result = $this->model->update($student);            }            Db::commit();        } catch (PDOException|Exception $e) {            Db::rollback();            $this->error($e->getMessage());        }        if (false === $result) {            $this->error(__('更新失败'));        }        $this->success();         }

来源地址:https://blog.csdn.net/Jian_Sir/article/details/130004153

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯