Read_Excel.php
2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<?php
/**
* 该文件为读取Excel文件导入数据库
* 需要数据库phpexcel下的student表,请注意表结构!
* 附加题:去除重复的学生账户,修改同一个学号下的学生信息(覆盖但不插入)
* Created by PhpStorm.
* User: shu
* Date: 2019-06-28
* Time: 22:48
*/
//接收前台文件
$ex = $_FILES['excel'];
//重设置文件名
$filename = time().substr($ex['name'],stripos($ex['name'],'.'));
$path = './excel_tmp/'.$filename;//设置移动路径
move_uploaded_file($ex['tmp_name'],$path);
//表用函数方法 返回数组
$exfn = readExcel($path);
if(count($exfn)<3){
exit('Excel没有任何数据');
}else{
array_splice($exfn,0,2);
$link = mysqli_connect('127.0.0.1','root','root','phpexcel');
mysqli_set_charset($link,'utf8mb4');
$sql = "INSERT INTO `phpexcel`.`student`( `sno`, `name`, `department`, `major`, `class`) VALUES (?,?,?,?,?);";
$mysqli_stmt = $link->prepare($sql);
//绑定参数
for($i =0 ;$i< count($exfn);$i++){
$tmpData = $exfn[$i];
$mysqli_stmt->bind_param("sssss",$tmpData[1],$tmpData[2],$tmpData[3],$tmpData[4],$tmpData[5]);
$result = $mysqli_stmt->execute();
if(!$result){
die("<script>alert('导入失败:".$mysqli_stmt->error."')</script>>");
}
}
echo "<script>alert('Excel数据导入数据库成功!')</script>";
}
//创建一个读取excel数据,可用于入库
function readExcel($path)
{
//引用PHPexcel 类
include_once('./PHPExcel_Croe/PHPExcel.php');
include_once('./PHPExcel_Croe/PHPExcel/IOFactory.php');//静态类
$type = 'Excel2007';//设置为Excel5代表支持2003或以下版本,Excel2007代表2007版
//创建读取Excel文件对象
$xlsReader = PHPExcel_IOFactory::createReader($type);
//设置文件读取为只读操作,以防其他代码干扰
$xlsReader->setReadDataOnly(true);
//
$xlsReader->setLoadSheetsOnly(true);
$Sheets = $xlsReader->load($path);
//开始读取上传到服务器中的Excel文件,返回一个二维数组
$dataArray = $Sheets->getSheet(0)->toArray();
return $dataArray;
}