1、先在github里面下载PHPexcel这个类库
2、解压之后把它复制到extend里面
控制器代码如下:
1 <?php 2 /** 3 * Created by PhpStorm. 4 * User: luxiao 5 * Date: 2017/5/8 6 * Time: 16:49 7 */ 8 namespace app\index\controller; 9 10 use think\Loader; 11 use think\Controller; 12 13 class Excel extends Controller 14 { 15 function excel() 16 { 17 $path = dirname(__FILE__); //找到当前脚本所在路径 18 Loader::import('PHPExcel.Classes.PHPExcel'); //手动引入PHPExcel.php 19 Loader::import('PHPExcel.Classes.PHPExcel.IOFactory.PHPExcel_IOFactory'); //引入IOFactory.php 文件里面的PHPExcel_IOFactory这个类 20 $PHPExcel = new \PHPExcel(); //实例化 21 22 $PHPSheet = $PHPExcel->getActiveSheet(); 23 $PHPSheet->setTitle("demo"); //给当前活动sheet设置名称 24 $PHPSheet->setCellValue("A1","姓名")->setCellValue("B1","分数");//表格数据 25 $PHPSheet->setCellValue("A2","张三")->setCellValue("B2","2121");//表格数据 26 $PHPWriter = \PHPExcel_IOFactory::createWriter($PHPExcel,"Excel2007"); //创建生成的格式 27 header('Content-Disposition: attachment;filename="表单数据.xlsx"'); //下载下来的表格名 28 header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); 29 $PHPWriter->save("php://output"); //表示在$path路径下面生成demo.xlsx文件 30 } 31 }
调用excel方法就可以生成一个表格了,后续的根据自己的需要自己去写代码.
PHPexcel 表格数据导入数据库 city 表,在这之前自己先创建好表单,我这次用的都是地址数据表做的测试:
1 function inserExcel() 2 { 3 Loader::import('PHPExcel.Classes.PHPExcel'); 4 Loader::import('PHPExcel.Classes.PHPExcel.IOFactory.PHPExcel_IOFactory'); 5 Loader::import('PHPExcel.Classes.PHPExcel.Reader.Excel5'); 6 //获取表单上传文件 7 $file = request()->file('excel'); 8 $info = $file->validate(['ext' => 'xlsx'])->move(ROOT_PATH . 'public' . DS . 'uploads'); //上传验证后缀名,以及上传之后移动的地址 9 if ($info) { 10 // echo $info->getFilename(); 11 $exclePath = $info->getSaveName(); //获取文件名 12 $file_name = ROOT_PATH . 'public' . DS . 'uploads' . DS . $exclePath; //上传文件的地址 13 $objReader =\PHPExcel_IOFactory::createReader('Excel2007'); 14 $obj_PHPExcel =$objReader->load($file_name, $encode = 'utf-8'); //加载文件内容,编码utf-8 15 echo "<pre>"; 16 $excel_array=$obj_PHPExcel->getsheet(0)->toArray(); //转换为数组格式 17 array_shift($excel_array); //删除第一个数组(标题); 18 $city = []; 19 foreach($excel_array as $k=>$v) { 20 $city[$k]['Id'] = $v[0]; 21 $city[$k]['code'] = $v[1]; 22 $city[$k]['path'] = $v[2]; 23 $city[$k]['pcode'] = $v[3]; 24 $city[$k]['name'] = $v[4]; 25 } 26 Db::name('city')->insertAll($city); //批量插入数据 27 } else { 28 echo $file->getError(); 29 }
前端代码:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 </head> 7 <body> 8 <form action="http://localhost/chexian5.0/index.php/index/excel/intoexcel" enctype="multipart/form-data" method="post"> 9 <input type="file" name="excel" /> 10 <input type="submit" value="导入"> 11 </form> 12 </body> 13 </html>