其实excel导入导出挺简单的,导出最简单!
其原理都是把数据读出来,导出是从数据库中读出数据,导入是从文件读出数据!
导出写入文件,导入写入数据库!
但是在导入表的时候,用的是PHPExcel,
不支持高版本的excel文件,支持2007的!
所以就尴尬啦!所以只能吧文件换成低版本才能导入!
前提:我的表是两个字段,name和pwd!
下面是导出:
//访问文件就直接下载啦 //导出XLS $result = mysql_query("select * from excel"); $str = "姓名\t密码\t\n"; $str = iconv('utf-8','gb2312',$str); while($row=mysql_fetch_array($result)){ $name = iconv('utf-8','gb2312',$row['name']); $pwd = iconv('utf-8','gb2312',$row['pwd']); $str .= $name."\t".$pwd."\t\n"; } $filename = date('Ymd').'.xls'; exportExcel($filename,$str);function exportExcel($filename,$content){ header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Content-Type: application/vnd.ms-execl"); header("Content-Type: application/force-download"); header("Content-Type: application/download"); header("Content-Disposition: attachment; filename=".$filename); header("Content-Transfer-Encoding: binary"); header("Pragma: no-cache"); header("Expires: 0"); echo $content;}
下面是导入:(两个关键文件reader.php和oleread.inc(这个文件在reader.php利用到 啦),这两个直接百度下就OK,PHPExcel)
1 include_once("excel/reader.php"); 2 $tmp = $_FILES['file']['tmp_name']; 3 if (empty ($tmp)) { 4 echo '请选择要导入的Excel文件!'; 5 exit; 6 } 7 8 $save_path = "xls/"; 9 $file_name = $save_path.date('Ymdhis') . ".xls";10 $data_values = '';11 if (copy($tmp, $file_name)) {12 $xls = new Spreadsheet_Excel_Reader();13 $xls->setOutputEncoding('utf-8');14 $xls->read($file_name);15 for ($i=2; $i<=$xls->sheets[0]['numRows']; $i++) {16 //$name = $xls->sheets[0]['cells'][$i][0];17 $name = $xls->sheets[0]['cells'][$i][1];18 $pwd = $xls->sheets[0]['cells'][$i][2];19 $data_values .= "('$name','$pwd'),";20 }21 $data_values = substr($data_values,0,-1); //去掉最后一个逗号22 $query = mysql_query("insert into excel (name,pwd) values $data_values");//批量插入数据表中23 if($query){24 echo '导入成功!';25 }else{26 echo '导入失败!';27 }28 }