1.下载PHPExcel,解压到目录PHPExcel。
2打开test.php引用连接数据库文件和PHPExcel文件,在php文件上面加上代码
include("conn.php");
require_once './PHPExcel/PHPExcel.php';
require_once './PHPExcel/PHPExcel/IOFactory.php';
require_once './PHPExcel/PHPExcel/Reader/Excel5.php';
$excelpath是excel的路径
$objReader = PHPExcel_IOFactory::createReader('excel5'); //use Excel5 for 2003 format
$excelpath='shipTemplate.xls'; //excel文件的名称
$objPHPExcel = $objReader->load($excelpath);
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow(); //取得总行数
$highestColumn = $sheet->getHighestColumn(); //取得总列数
逐行循环读取excel,并加入分隔符。
for($j=2;$j<=$highestRow;$j++) //从第二行开始读取数据
{
$str="";
for($k='A';$k<=$highestColumn;$k++) //从A列读取数据
{
$str .=$objPHPExcel->getActiveSheet()->getCell("$k$j")->getValue().'|*|';//读取单元格
}
$str=mb_convert_encoding($str,'utf-8','auto');//
$strs = explode("|*|",$str);
//var_dump($strs);exit;
$sql = "insert into test (Id,khdh,kg,sjrname,sjriphone,sjrsheng,sjraddress,sjryb,jjrname,jjriphone,jjraddress,jjryb) values ('','{$strs[0]}','{$strs[1]}','{$strs[2]}','{$strs[3]}','{$strs[4]}','{$strs[5]}','{$strs[6]}','{$strs[7]}','{strs[8]}','{strs[9]}','{strs[10]}')";
if(!mysql_query($sql,$conn))
{
echo 'excel error';
}
else{
echo 'chenggong';
}
}
5.文件conn.php
$conn=mysql_connect("localhost","root","root") or die("数据库服务器连接错误".mysql_error());
mysql_select_db("shipTemplate",$conn) or die("数据库访问错误".mysql_error());
mysql_query("set character set utf8");
mysql_query("set names utf8");
6.excel原图
导入数据以后