應(yīng)該說介紹了利用phpexcel插件來實(shí)現(xiàn)數(shù)據(jù)庫的導(dǎo)入與導(dǎo)入功能,本文章主要是告訴你把excel導(dǎo)入到mysql數(shù)據(jù)庫的方法.
先下載,下載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');//此處設(shè)置編碼,一般都是gbk模式
- $data->read('Book1.xls');//文件路徑
- error_reporting(E_ALL ^ E_NOTICE);
- //這里我就只循環(huán)輸出excel文件的內(nèi)容了,要入庫,只要把輸出的地方,寫一段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(); // 取得總行數(shù)
- $highestColumn = $sheet->getHighestColumn(); // 取得總列數(shù)
- $k = 0;
- //循環(huán)讀取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);
- }
代碼實(shí)例cvs導(dǎo)入到數(shù)據(jù)庫,把csv導(dǎo)入到數(shù)據(jù)庫,代碼如下:
- 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',',')){
- //開源代碼Vevb.com
- insert_data ($data[0],$data[1],$data[2],$data[3],$data[4]);
- echo "<font color = #ff0000 size = 20>數(shù)據(jù)導(dǎo)入成功!</font><br><br>";
- }
- fclose ($fp);
- $time_end = getmicrotime();
- $time = $time_end - $time_start;
- echo "程序執(zhí)行時間:".$time."秒";
新聞熱點(diǎn)
疑難解答