PHP将Excel内容导入mysql数据库
注:本文技术含量较低,是通过别人写的一个类来完成的,所以不要用金砖砸我。小生我怕怕!!!
1、首先需要一个读取excel的类(在附件中)
2、附件中有3个文件在excel目录中有2文件是读取excel的文件,excel.php是我的一个测试文件
2、excel.php文件测试代码如下:
<?php
include'conn.php'; // 数据库连接文件,引用你自己的连接数据库文件
if($_POST[submit]){
if($_POST['upfile']==""){
echo "<script>alert('对不起请选择EXCEL文件');location='execld.php';</script>";
}else{
require_once 'Excel/reader.php'; //注意这里的引用位置
$data = new Spreadsheet_Excel_Reader();
$data->setOutputEncoding('gbk'); //指定编码很重要
$data->read($_POST['upfile']);
error_reporting(E_ALL ^ E_NOTICE);
mysql_query('set names "gbk"'); //指定编码很重要
for ($i = 1; $i <= $data->sheets[0]['numRows']; $i++) {
$sql = "INSERT INTO tuhaoinfo VALUES('". //开始读取excel文件的内容并插入数据库
$data->sheets[0]['cells'][$i][1]."','".
$data->sheets[0]['cells'][$i][2]."','". <---指定列此处是共9列根据你的内容填写
$data->sheets[0]['cells'][$i][3]."','".
$data->sheets[0]['cells'][$i][4]."','".
$data->sheets[0]['cells'][$i][5]."','".
$data->sheets[0]['cells'][$i][6]."','".
$data->sheets[0]['cells'][$i][7]."','".
$data->sheets[0]['cells'][$i][8]."','".
$data->sheets[0]['cells'][$i][9]."')";
$zh=mysql_query($sql);
}
if($zh){
echo "<script>alert('添加成功');location='execld.php'</script>";
}else{ //判断添加是否成功
echo "<script>alert('添加失败');location='execld.php'</script>";
}
}
}
?>
<form action="" method="post" name="imp">
<input type="file" name="upfile" onpropertychange='checkFileType(this.value);' />
<input type="submit" name="submit"/>
</form>
<script type="text/javascript"> //判断用户选择的文件类型
function checkFileType(str){
var pos = str.lastIndexOf(".");
var lastname = str.substring(pos,str.length);
var resultName=lastname.toLowerCase();
if ('.xls'!=resultName.toString()){alert('只能选择xls文件,您上传的文件类型为'+lastname+',请重新选择);
imp.submit.disabled=true;
}else{
imp.submit.disabled=false;
}
}
</script>
4、数据库内容根据自己的实际情况来定,在附件中有一个我自己的数据库字段表
特别注意:前端和后台数据库的字符编码一定要一致。
//exp.php 用于导出 <?php
|
转载于:https://blog.51cto.com/im9527/706989