PHP导入Excel到MySQL的方法

PHP-ExcelReader,下载地址: http://sourceforge.net/projects/phpexcelreader

注意点

reader.php 中的下面这行要修改 
1、将 require_once ‘Spreadsheet/Excel/Reader/OLERead.php’;
改为 require_once ‘oleread.inc’;

2、require_once ‘oleread.inc’也可以和拷贝出来放到reader的文件最前面合并为一个文件

3、$data->setOutputEncoding(‘utf-8’)也可以这样用,我的项目都是utf-8的编码,开始用的就是上面的写法$data->setOutputEncoding(’CP936′);结果是,导入数据库老是说编码错误。最后设成utf-8解决了。

上传Excel界面代码:

upExcel.php

<?php
	header("Content-Type:text/html;charset=utf-8"); //设置字体编码,避免中文乱码
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>导入测试</title> 
</head> 

<body> 

<script> 
function import_check(){ 
    var f_content = form1.file.value; 
    var fileext=f_content.substring(f_content.lastIndexOf("."),f_content.length) 
        fileext=fileext.toLowerCase() 
     if (fileext!='.xls') 
        { 
         alert("对不起,导入数据格式必须是xls格式文件哦,请您调整格式后重新上传,谢谢 !");            
         return false; 
        } 
} 
</script> 

<table width="98%" border="0" align="center" style="margin-top:20px; border:1px solid #9abcde;"> 
    <form id="form1" name="form1" enctype="multipart/form-data" method="post" action="insert.php"> 
        <tr> 
            <td width="18%" height="50"> 选择你要导入的数据表:</td> 
            <td width="82%">
				<label> 
					<input name="file" type="file" id="file" size="50" /> 
				</label> 
                <label> 
					<input name="button" type="submit" class="nnt_submit" id="button" value="导入数据"  onclick="import_check();"/> 
                </label> 
			</td> 
        </tr> 
	</form>
</table> 
</body> 
</html> 


实现上传写入数据库的代码insert.php

<?php
header("Content-Type:text/html;charset=utf-8"); //设置字体编码,避免中文乱码
require_once("../db_config.php");
require_once 'Excel/reader.php'; 
error_reporting(E_ALL ^ E_NOTICE); 

//ini_set('max_execution_time', '100');   //php运行时间为30秒,当数据量大时,会出现超时而导致无法全部导入的情况。

if($_POST)
{ 
	$Import_TmpFile = $_FILES['file']['tmp_name']; 
//	$Import_TmpFile = 'http://test998-merchphoto.stor.sinaapp.com/test.xls'; 

	$data = new Spreadsheet_Excel_Reader(); 
	$data->setOutputEncoding('utf-8'); 
	$data->read($Import_TmpFile); 
    $count =0;    
	for($i= 1; $i<= $data->sheets[0]['numRows']; $i++)
	{ 
		$sql= "INSERT INTO test_xls(id,tm,name) VALUES('". $data->sheets[0]['cells'][$i][1]."','". $data->sheets[0]['cells'][$i][2]."','". $data->sheets[0]['cells'][$i][3]."')"; 
		echo $sql."</br>";
		if(mysql_query($sql))
		{
			$count++;		
		}		
	} 
    echo "<script>alert('成功导入".$count."条数据');</script>"; 
} 
?> 


mysql 表:



excel:



参考资料:

1、http://jason2016.blog.51cto.com/892969/289411

2、http://www.cnblogs.com/phpzxh/archive/2009/09/16/1568133.html

3、http://blog.csdn.net/china_skag/article/details/7098473


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。