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>

