//使用PHPExcel-1.8实现导入(下载PHPExcel-1.8):导入excel 后缀名必须是.xls
1.
<form method="post" action="XX.php" enctype="multipart/form-data" style="background:#E9F2FB;">
<input type="file" name="fileex" />
<input type="submit" value="导入" />
</form>
2.
<?php
header("Content-type: text/html; charset=utf-8");
mysql_query("SET NAMES 'utf-8'");
date_default_timezone_set('PRC');
$mysql_database='XXX';
$link = mysql_connect("localhost","root","");
if(!$link){
echo '数据库连接失败...<br>';
exit(-1);
}else{
mysql_select_db($mysql_database);
}
include "PHPExcel-1.8/Classes/PHPExcel.php";
require_once 'PHPExcel-1.8/Classes/PHPExcel/IOFactory.php';
require_once 'PHPExcel-1.8/Classes/PHPExcel/Reader/Excel5.php';
if (empty($_FILES['fileex']["name"])){echo "<script>alert('您没有选择文件!请选择文件后导入');history.go(-1);</script>";}
@$file = $_FILES["fileex"];
//var_dump($file);exit();
//$data=date('Y-m-d');
$name = $file['name'];
$type = strtolower(substr($name,strrpos($name,'.')+1));
if(!is_uploaded_file($file['tmp_name'])){
echo "222";
}
//自定义文件名称
@$array=$_FILES["file"]["type"];
$array=explode("/",$array);
if (!is_dir("excel/")){
mkdir("excel/");
}
$url="excel/".$name;
//var_dump($url);exit();
if (file_exists($url.$_FILES["fileex"]["name"])){
//echo $_FILES["file"]["name"] . " already exists. ";
}else{
//var_dump(1123);exit();
//$url=$url.$_FILES["fileex"]["name"];
move_uploaded_file($_FILES["fileex"]["tmp_name"],$url);
// echo "Stored in: " . $url;
}
$filename=$url;
//var_dump($filename);exit();
//exit();
$objReader = PHPExcel_IOFactory::createReader('Excel5');//use excel2007 for 2007 format
//var_dump($objReader);exit();
//$data = new Spreadsheet_Excel_Reader(); $data->setOutputEncoding('utf-8'); $resval = $data->read($sFileName);var_dump($resval);exit();
$objPHPExcel = $objReader->load($filename); //$filename可以是上传的文件,或者是指定的文件
//var_dump($objPHPExcel);exit();
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow(); // 取得总行数
//var_dump($highestRow);exit();
$highestColumn = $sheet->getHighestColumn(); // 取得总列数
$k = 0;
// var_dump($highestRow);exit();
//循环读取excel文件,读取一条,插入一条
for($j=2;$j<=$highestRow;$j++)
{
$a = $objPHPExcel->getActiveSheet()->getCell("A".$j)->getValue();//获取A列的值
$b = $objPHPExcel->getActiveSheet()->getCell("B".$j)->getValue();//获取B列的值
//$sql = "INSERT INTO table VALUES(".$a.",".$b.")";
//mysql_query($sql);
//var_dump($a);
}
?>