如果要使用phpExcelReader将Excel 数据导入到mysql 数据库,请读者点击这个文章查看。
使用phpExcelReader将Excel 数据导入到mysql 数据库。
下面我们介绍另一种方法来实现导入Excel到MySQL数据库。
1、到官网http://phpexcel.codeplex.com/下载PHPExcel类库,我目前使用的是1.7.9版本。如图:

2、直接上代码。
(1)、conn.php文件(这个不用介绍,你懂得):
PHP Code复制内容到剪贴板
$mysql=mysql_connect("localhost","root","root");
mysql_select_db("test",$mysql);
mysql_query("set names GBK");
(2)、HTML页面部分:index.php文件(表单提交页面):
XML/HTML Code复制内容到剪贴板
<form name="form2" method="post" enctype="multipart/form- data" action="upload_excel.php">
<input type="hidden" name="leadExcel" value="true">
<table align="center" width="90% " border="0">
<tr>
<td>
<input type="file" name="inputExcel"><input type="submit" name="import" value="导入数据 ">
</td>
</tr>
</table>
</form>
(3)、表单处理处理程序部分:upload_excel.php文件:
PHP Code复制内容到剪贴板
include("conn.php");
include("function.php");
if($_POST ['import']=="导入数据 "){
$leadExcel=$_POST['leadExcel'];
if($leadExcel == "true")
{
$filename = $HTTP_POST_FILES['inputExcel'] ['name'];
$tmp_name = $_FILES ['inputExcel']['tmp_name'];
$msg = uploadFile($filename,$tmp_name);
echo $msg;
}
}
(4)、函数部分:function.php文件:
PHP Code复制内容到剪贴板
function uploadFile($file,$filetempname)
{
$filePath = 'upFile/';
$str = "";
set_include_path('.'. PATH_SEPARATOR .'E:\php\AppServ\www\91ctcStudy\PHPExcelImportSQl2 \PHPExcel' . PATH_SEPARATOR .get_include_path());
require_once 'PHPExcel.php';
require_once 'PHPExcel\IOFactory.php';
require_once 'PHPExcel\Reader\Excel2007.php';
$filename=explode(".",$file);
$time=date("y-m-d-H-i- s");
$filename [0]=$time;
$name=implode (".",$filename);
$uploadfile=$filePath.$name;
$result=move_uploaded_file($filetempname,$uploadfile);
if($result)
{
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objPHPExcel = PHPExcel_IOFactory::load($uploadfile);
$sheet = $objPHPExcel- >getSheet(0);
$highestRow = $sheet- >getHighestRow();
$highestColumn = $sheet- >getHighestColumn();
for($j=2;$j<=$highestRow;$j++)
{
for($k='A';$k<=$highestColumn;$k++)
{
$str .= iconv('utf-8','gbk',$objPHPExcel->getActiveSheet()->getCell("$k$j")->getValue()).'\\';//读 取单元格
}
//explode:函 数把字符串分割为数组。
$strs =& nbsp;explode("\\",$str);
//var_dump ($strs);
//die();
$sql =&n bsp;"INSERT INTO z_test_importexcel(duty_date,name_am,name_pm) VALUES ('".$strs[0]."','".$strs[1]."','".$strs[2]."')";
//echo $ sql;
mysql_query ("set names GBK");//这就是指定数据库字 符集,一般放在连接数据库后面就系了
if(! mysql_query($sql)){
& nbsp; return false;
}
$str =&n bsp;"";
}
unlink ($uploadfile); //删除上传的excel文件
$msg = "导入成 功!";
}else{
$msg = "导入失 败!";
}
return $msg;
}
关于这个函数,参考了http://blog.csdn.net/grassroots20 11/article/details/8104604该博友的文章,但是,该博友的写法,我认为有问题,至少 ,我用的
$objPHPExcel = $objReader->load ($uploadfile);
这一句写法,在运行的时候,会出现:

或者是PHPExcel类库官方后来升级了,调用方法需要改正一下吧,具体笔者就没考究了。
3、通过上面的几个步骤,读者再分别准备一个xls和xlsx文档就可以了,系统运行效果:

附件下载:完整DEMO下载(已含PHPExcel类库)附件下载:完整DEMO下载(已含PHPExcel类库)