前提下载好phpexcel文件。
1.在项目目录下将解压下来的phpexcel文件夹中的class文件夹放入;
2.建立前端上传界面index.html
<!DOCTYPE html>
<html>
<head>
<title>上传文件</title>
</head>
<body>
<form action="deal.php" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file">
<input type="submit" name="submit" value="daoru" style="width: 50px">
</form>
</body>
</html>
3.建立连接数据库页面database.php
<?php
$Server="localhost";
$User="root";
$pw="**";//密码
$db="**";//数据库名
$con=mysqli_connect($Server,$User,$pw,$db);
// 检查连接
if (!$con)
{
die("连接错误: " . mysqli_connect_error());
}
else
echo "数据库连接成功"."<br>";
//设置客户端和连接字符集
mysqli_set_charset($con,"utf8");
?>
4.建立后端处理上传文件的页面deal.php
<?php
header("content-type:text/html;charset=utf-8");
include("database.php");
require_once './Classes/PHPExcel/IOFactory.php';
require_once './Classes/PHPExcel.php';
require_once './Classes/PHPExcel/Reader/Excel5.php';
$n=$_FILES["file"]["name"];//获取上传文件名
$type=strstr($_FILES["file"]["name"],".");//判断文件格式
$exceltype="";
if(strtolower($type)==".xls")
$exceltype="Excel5";
if(strtolower($type)==".xlsx")
$exceltype="Excel2007";
if(strtolower($type)==".csv")
$exceltype="CSV";
$objReader = PHPExcel_IOFactory::createReader($exceltype);
$objPHPExcel = $objReader->load($_FILES["file"]["tmp_name"]);
$sheet = $objPHPExcel->getSheet(0);//获取第一个表
$highestRow = $sheet->getHighestRow(); // 取得总行数
$check=1;
echo "<br>";
//循环读取excel文件,读取一条,插入一条
for ($j = 2; $j <= $highestRow; $j++) { //第一行为字段,可以忽视,从第二行开始.并根据需要获取相应列的值
$id = $objPHPExcel->getActiveSheet()->getCell("A" . $j)->getValue();//获取A列的值
echo $id."<br>;
$name = $objPHPExcel->getActiveSheet()->getCell("B" . $j)->getValue();//获取B列的值
echo $name."<br>";
$sql="insert into ** values('$id','$name')";//**为表名
if(!mysqli_query($con,$sql))
$check=0;
}
if($check==1)
echo "导入成功!";
else
echo "导入失败!";
?>
4.注意数据库中表的字段要和插入数据的字段对应。要是有中文数据插入数据库中的表,点击查看我另外一篇博文:解决mysql数据库不能插入中文。