PHP用PHPExcel.php插件上传Excel文件导入数据到MySQL数据库

一、前端代码,及样式

 1      1、“导入”方式仅支持<span style="color:#ff0000;font-weight:600;">XLS或者XLSX</span> 这种格式文档;<br>
 2 
 3       2、*.xls 或者*.xlsx 要导入的文档必须包含所需字段的信息,不然有可能导入不成功;<br>
 4 
 5       3、单次导入文件不超过5M。<br><br><br>
 6 
 7       <form name="form1" enctype="multipart/form-data" method="post" action="import_excel.php" style="margin-bottom:400px;">
 8         文档编码:
 9           <label style="display:inline-block;width:auto;margin-right:10px;">
10           <select name="file_encoding" style="margin-bottom:0;height:34px;">
11             <option value="gbk">简体中文</option>
12             <option value="utf8">UTF-8</option>
13           </select>
14           </label>
15           <label style="display:inline-block;width:auto;margin-right:10px;">
16           <input type="file" name="excel" class="btn" style="height:24px;line-height:24px;">
17               </label>
18             <label style="display:inline-block;width:auto;">
19             <input type="submit"  value="确认上传" class="btn btn-success" style="line-height:24px;">
20             </label>
21     </form>

二、后端代码   import_excel.php

  1 <?php 
  2 include("../include/init.php");
  3 include("check_user.php");
  4 include('./phpexcel/PHPExcel.php');//引入PHPExcel库文件
  5 
  6 $user_nichen = isset($_SESSION['user_nichen']) ? $_SESSION['user_nichen'] : "";
  7 
  8  if (!empty($_FILES['excel']['name'])) {
  9         $fileName = $_FILES['excel']['name'];    //得到文件全名
 10         $dotArray = explode('.', $fileName);    //把文件名安.区分,拆分成数组
 11         $type = end($dotArray);
 12         if ($type != "xls" && $type != "xlsx") {
 13             $ret['res'] = "0";
 14             $ret['msg'] = "不是Excel文件,请重新上传!";
 15             return json_encode($ret);
 16         }
 17 
 18         //取数组最后一个元素,得到文件类型
 19         $uploaddir = "../uploads2/" . date("Y-m-d") . '/';//设置文件保存目录 注意包含
 20         if (!file_exists($uploaddir)) {
 21             mkdir($uploaddir, 0777, true);
 22         }
 23  
 24         $path = $uploaddir . md5(uniqid(rand())) . '.' . $type; //产生随机文件名
 25         //$path = "images/".$fileName; //客户端上传的文件名;
 26         //下面必须是tmp_name 因为是从临时文件夹中移动
 27         move_uploaded_file($_FILES['excel']['tmp_name'], $path); //从服务器临时文件拷贝到相应的文件夹下
 28  
 29         $file_path = $path;
 30         if (!file_exists($path)) {
 31             $ret['res'] = "0";
 32             $ret['msg'] = "上传文件丢失!" . $_FILES['excel']['error'];
 33             return json_encode($ret);
 34         }
 35 
 36         //文件的扩展名
 37         $ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));
 38         if ($ext == 'xlsx') {
 39             $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
 40             $objPHPExcel = $objReader->load($file_path, 'utf-8');
 41         } elseif ($ext == 'xls') {
 42             $objReader = \PHPExcel_IOFactory::createReader('Excel5');
 43             $objPHPExcel = $objReader->load($file_path, 'utf-8');
 44         }
 45  
 46         $sheet = $objPHPExcel->getSheet(0);
 47         $highestRow = $sheet->getHighestRow(); // 取得总行数
 48         $highestColumn = $sheet->getHighestColumn(); // 取得总列数
 49         $ar = array();
 50         $i = 0;
 51         $importRows = 0;
 52 
 53 // 获取一行的数据
 54 for ($row = 1; $row <= 1; $row++){
 55 
 56 $rowData = $sheet->rangeToArray('A1:' . $highestColumn . $row, NULL, TRUE, FALSE);
 57 
 58 //var_dump($rowData[0]);echo "<br>";
 59 
 60     
 61     foreach ($rowData[0] as $key => $value) {
 62 
 63            if(trim($value) == "姓名"){
 64                     $col1 = PHPExcel_Cell::stringFromColumnIndex($key); //获取列号
 65            }
 66            if(trim($value) == "性别"){
 67                     $col2 = PHPExcel_Cell::stringFromColumnIndex($key);//获取列号
 68            }
 69            if(trim($value) == "登记号"){
 70                     $col3 = PHPExcel_Cell::stringFromColumnIndex($key);//获取列号
 71            }
 72            if(trim($value) == "制单时间"){
 73                     $col4 = PHPExcel_Cell::stringFromColumnIndex($key);//获取列号
 74            }
 75     }
 76 
 77 }
 78 
 79 
 80         for ($j = 2; $j <= $highestRow; $j++) {
 81             $importRows++;
 82 
 83             $bianhao =(string)$objPHPExcel->getActiveSheet()->getCell($col3.$j)->getValue(); //需要导入的bianhao
 84             $name =(string)$objPHPExcel->getActiveSheet()->getCell($col1.$j)->getValue(); //需要导入的name
 85             $xingbie = (string)$objPHPExcel->getActiveSheet()->getCell($col2.$j)->getValue();//需要导入的xingbie
 86             $date = (string)$objPHPExcel->getActiveSheet()->getCell($col4.$j)->getFormattedValue();//需要导入的date  即制单时间
 87             $date =date("Y-m-d H:i:s",strtotime($date));
 88      
 89       
 90             //echo $date; exit;
 91 
 92             //组装的添加数据
 93                    $data = array(
 94                        "name" =>$name,
 95                        "xingbie" =>$xingbie,
 96                        "bianhao" =>$bianhao,
 97                        "date" =>$date,
 98 
 99                        "daoshi" =>$user_nichen,
100                        "date2" =>date("Y-m-d H:i:s")
101                   
102 
103 
104                      );
105 
106                     $affect_id= insert("{$yy_}hufu",$data);
107 
108                     if ($affect_id) {
109                        $i++;
110                      }
111         }
112 
113 
114 
115         if ($i > 0) {
116 
117                             //写导入日记    /组装的添加数据
118                            $data = array(
119                                "excel_name" =>$fileName,
120                                
121                                "daoshi" =>$user_nichen,
122                                "date2" =>date("Y-m-d H:i:s")
123                              );
124 
125                             $affect_id2= insert("{$yy_}log_import",$data);
126                             
127             show_msg("导入完毕!","form_history_list.php");
128         }
129 
130 } else {
131    show_msg("操作失败");
132    exit;
133    
134 }
135 
136 
137 
138 ?>

 

 

 
posted @ 2021-03-06 09:41  pensive2019  阅读(1229)  评论(0)    收藏  举报