> 文章列表 > fastadmin+phpspreadsheet实现导出和导入

fastadmin+phpspreadsheet实现导出和导入

fastadmin+phpspreadsheet实现导出和导入

在对应的index.html页面添加导航按钮,导出数据,直接在<a href=""> 添加对应方法,如果使用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();}