應該說介紹了利用phpexcel插件來實現數據庫的導入與導入功能,本文章主要是告訴你把excel導入到mysql數據庫的方法.
先下載
下載phpexcel文件,地址:phpexcel.codeplex.com/
在reader.php文件中找到以下類似代碼(第一行既是),改成正確的oleread.php路徑即可:require_once 'oleread.php';
然後新建一個php文件引入reader.php,
代碼如下:
<?php
require_once 'Excel/reader.php';
$data = new Spreadsheet_Excel_Reader();
$data->setOutputEncoding('gbk');//此處設置編碼,一般都是gbk模式
$data->read('Book1.xls');//文件路徑
error_reporting(E_ALL ^ E_NOTICE);
//這裡我就只循環輸出excel文件的內容了,要入庫,只要把輸出的地方,寫一段mysql語句即可~
for ($i = 1; $i <= $data->sheets[0]['numRows']; $i++) {
for ($j = 1; $j <= $data->sheets[0]['numCols']; $j++) {
echo """.$data->sheets[0]['cells'][$i][$j]."",";
}
echo "n";
}
?>
代碼示例
require_once 'phpexcel/Classes/PHPExcel.php';
require_once 'phpexcel/Classes/PHPExcel/IOFactory.php';
require_once 'phpexcel/Classes/PHPExcel/Reader/Excel5.php';
$objReader = PHPExcel_IOFactory::createReader('Excel5');//use excel2007 for 2007 format
$objPHPExcel = $objReader->load($filename); //$filename可以是上傳的文件,或者是指定的文件
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow(); // 取得總行數
$highestColumn = $sheet->getHighestColumn(); // 取得總列數
$k = 0;
//循環讀取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);
}
代碼實例cvs導入到數據庫
把csv導入到數據庫。
代碼如下 復制代碼function getmicrotime(){
list($usec, $sec) = explode(" ",microtime());
return ((float)$usec + (float)$sec);
}
$time_start = getmicrotime();
include ("connectdb.php");
function insert_data ($id,$summary,$description,$additional_information,$category)
{
$my_query1 = "insert into mantis_bug_text_table (id,description,additional_information)
values ('$id','$description','$additional_information')";
$first = mysql_query($my_query1);
$my_query2 = "insert into mantis_bug_table (id,project_id,summary,bug_text_id) values ('$id','$category','$summary','$id')";
$second = mysql_query($my_query2);
return;
}
$fp = fopen("test.csv","r");
while($data = fgetcsv($fp,'1000',',')){
insert_data ($data[0],$data[1],$data[2],$data[3],$data[4]);
echo "<font color = #ff0000 size = 20>數據導入成功!</font><br><br>";
}
fclose ($fp);
$time_end = getmicrotime();
$time = $time_end - $time_start;
echo "程序執行時間:".$time."秒";
更多詳細內容請查看:http://www.bKjia.c0m/phper/php-database/excel-mysql.htm