有時候如果有大量的數據需要導入到數據庫,最低級的辦法就是,一個一個的手動添加,而日常生活中,常常用表格來記錄,能不能讓PHP直接讀取一個excel表格,然后,將表格中的內容,全部導入數據庫呢,這樣子,可以節省大量的時間。
php-excel-reader是一個讀取excel的類,可以很輕松的使用它讀取excel文件。
首先要下載有關的文件:
鏈接:http://pan.baidu.com/s/1i5990hv 密碼:4npd
其余文件為事例文件,請認真分析源碼。
表格對應內容:
1:引入類,創建對象,設置讀取文件的目錄
<?php error_reporting(E_ALL ^ E_NOTICE);require_once 'excel_reader2.php';$data = new Spreadsheet_Excel_Reader();//創建對象$data->setOutputEncoding('UTF-8');//設置編碼格式$data->read("example.xls");//讀取excel文檔
<?phperror_reporting(E_ALL ^ E_NOTICE);require_once 'excel_reader2.php';$data = new Spreadsheet_Excel_Reader();//創建對象$data->setOutputEncoding('UTF-8');//設置編碼格式$data->read("example.xls");//讀取excel文檔echo "<pre>";print_r($data->sheets);echo "</pre>";
運行結果如下
3:如果要讀取,數組中的詳細內容,給出幾個例子
<?phperror_reporting(E_ALL ^ E_NOTICE);require_once 'excel_reader2.php';$data = new Spreadsheet_Excel_Reader();//創建對象$data->setOutputEncoding('UTF-8');//設置編碼格式$data->read("example.xls");//讀取excel文檔//echo "<pre>";//print_r($data->sheets);//echo "</pre>";echo $data->sheets[0]['numRows']."行<br>";//讀出一共幾行echo $data->sheets[0]['numCols']."列<br>";//讀出一共幾列echo $data->sheets[0]['cells'][1][1]."<br>";//讀出第一行第一列的內容print_r($data->sheets[0]['cells'][1]);//第一行的數據echo "<br>";echo implode(",",$data->sheets[0]['cells'][1])."<br>";//去除第一行的數據,每個中間添加分隔符for($i=1;$i<=$data->sheets[0]['numCols'];$i++)//一次讀出第一行的所有數據{ echo $data->sheets[0]['cells'][1][$i]." ";}echo "<br>";echo "<br>";//讀出所有數據for ($i = 1; $i <= $data->sheets[0]['numRows']; $i++) { //$data->sheets[0]['numCols']為Excel列數 for ($j = 1; $j <= $data->sheets[0]['numCols']; $j++) { //顯示每個單元格內容 echo $data->sheets[0]['cells'][$i][$j].' '; } echo '<br>';}
注意上述,echo implode(",",$data->sheets[0]['cells'][1])."<br>";//去除第一行的數據,每個中間添加分隔符,,的應用,這樣就可以,直接向數據庫插入一整行的數據了
注:
dump(),它可以將excel內容以html格式輸出:
echo $data->dump(true,true);
<?phperror_reporting(E_ALL ^ E_NOTICE);require_once 'excel_reader2.php';$data = new Spreadsheet_Excel_Reader("example.xls");?><html><head><style>table.excel { border-style:ridge; border-width:1; border-collapse:collapse; font-family:sans-serif; font-size:12px;}table.excel thead th, table.excel tbody th { background:#CCCCCC; border-style:ridge; border-width:1; text-align: center; vertical-align:bottom;}table.excel tbody th { text-align:center; width:20px;}table.excel tbody td { vertical-align:bottom;}table.excel tbody td { padding: 0 3px; border: 1px solid #EEEEEE;}</style></head><body><?php echo $data->dump(true,true); ?></body></html>
鄭重聲明:本文版權歸原作者所有,轉載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯系我們修改或刪除,多謝。
新聞熱點
疑難解答