php中将excel写入mysql数据库的示例

添加文件的表单

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<title>添加excel入库</title>

</head>


<body>

<form action="insert.php" enctype="multipart/form-data" method="post">

<input type="file" value="" name="file">

<input type="submit" value="提交" >

</form>

</body>

</html>




php代码

<?php

header("content-type:text/html;charset=utf-8");

//导入Xls处理流程:选择xls文件->上传xls文件到服务器->通过PHP-ExcelReader解析excel->批量入库。


include_once("./reader.php"); //引入PHP-ExcelReader 

$tmp = $_FILES['file']['tmp_name']; 

if (empty ($tmp)) { 

echo '请选择要导入的Excel文件!';     

exit; 



$dsn = "mysql:host=localhost;dbname=test";

$db = new PDO($dsn, 'root', '123');

//$count = $db->exec("insert into xls(id,name,content,decs)values()");



$save_path = "xls/"; 

$file_name = $save_path.date('Ymdhis') . ".xls"; //上传后的文件保存路径和名称 

if (copy($tmp, $file_name)) {  

$xls = new Spreadsheet_Excel_Reader();     

$xls->setOutputEncoding('utf-8');  //设置编码     

$xls->read($file_name);  //解析文件   

//echo $xls->sheets[0]['numRows'];die;






/*

for ($i=2; $i<=$xls->sheets[0]['numRows']; $i++) {         

$name = $xls->sheets[0]['cells'][$i][0]; 

$sex = $xls->sheets[0]['cells'][$i][1];        

$age = $xls->sheets[0]['cells'][$i][2];         

$data_values .= "('$name','$sex','$age'),";     

}  

*/ 



for ($i=1; $i<=$xls->sheets[0]['numRows']; $i++) {         

$id = $xls->sheets[0]['cells'][$i][1];

$name = $xls->sheets[0]['cells'][$i][2];

$content = $xls->sheets[0]['cells'][$i][3]; 

$decs = $xls->sheets[0]['cells'][$i][4];

@$data_values .= "($id,'$name','$content','$decs'),";     





$data_values = substr($data_values,0,-1); //去掉最后一个逗号     

$query = $db->exec("insert into xls (xid,name,content,decs) values $data_values");//批量插入数据表中 

if($query){

echo '导入成功!';     

}else{ 

echo '导入失败!';     

}

?>


你可能感兴趣的:(mysql,数据库,Excel)