用 PHP 讀寫 Excel 檔案
九月 18th, 2008
PHP 讀寫 Excel 的方法有很多種,例如先轉成 CSV 格式來讀,然後用特定符號去分隔欄位。但是如果遇到欄位格式不固定的 Excel 就很麻煩了,所以需要可以直接操作 excel 的方法,方便直接指定要取某欄某列的值。
如果是 Windows 系統的話可以使用 COM 元件去讀取,但缺點就是只能在 Windows 上跑,失去了跨平台性,所以也有人另外寫出可以讀寫 Excel 的類別,這次要推薦的是 PHPExcel,PHPExcel 的功能非常強大,原本就支援 Excel 2007,新版中也能讀取 Excel 2003 舊版的 Excel 囉!
從 PHPExcel 下載回來的檔案中就包含不少範例,但是讀取的部份很簡略,所以底下貼個讀取 Excel 內容的範例:
<?php
set_include_path(get_include_path() . PATH_SEPARATOR . './Classes/');
include 'PHPExcel/IOFactory.php';
$reader = PHPExcel_IOFactory::createReader('Excel5'); // 讀取舊版 excel 檔案
$PHPExcel = $reader->load("course_table.xls"); // 檔案名稱
$sheet = $PHPExcel->getSheet(0); // 讀取第一個工作表(編號從 0 開始)
$highestRow = $sheet->getHighestRow(); // 取得總列數
// 一次讀取一列
for ($row = 2; $row <= $highestRow; $row++) {
for ($column = 1; $column <= 9; $column++) {
$val = $sheet->getCellByColumnAndRow($column, $row)->getValue();
echo $val . ' ';
}
echo "<br />";
}
不好意思,其實我是希望讀出來的資料能塞進mySQL,用getCellByColumnAndRow($column, $row)會讀出好多筆重複的....請問能舉個簡單例子嗎 ? 謝謝
excel裡的日期讀進來會變成數字,要如何轉換呢?
文件上寫
In Excel, dates are stored as numeric values counting the number of days elapsed since 1900-01-01. For example, the date '2008-12-31' is represented as 39813.
Oh my goodness! a tremendous article dude. Thank you Nonetheless I'm experiencing difficulty with ur rss . Don’t know why Unable to subscribe to it. Is there anyone getting similar rss downside? Anyone who is aware of kindly respond. Thnkx
@Johnny
找了一個早上,解決了,供參考嚕~ (遇到一樣問題的flylon)
// phpExcel轉日期函式
function excelTime($days, $time=false){
if(is_numeric($days)){
//based on 1900-1-1
$jd = GregorianToJD(1, 1, 1970);
$gregorian = JDToGregorian($jd+intval($days)-25569);
$myDate = explode('/',$gregorian);
$myDateStr = str_pad($myDate[2],4,'0', STR_PAD_LEFT)
."-".str_pad($myDate[0],2,'0', STR_PAD_LEFT)
."-".str_pad($myDate[1],2,'0', STR_PAD_LEFT)
.($time?" 00:00:00":'');
return $myDateStr;
}
return $days;
}
Hi Johnny,
I have a problem when executing your codes. It returns a fatal error as below:
"Fatal error: Call to undefined function spl_autoload_register() in XXX/Classes\PHPExcel\Autoloader.php on line 40"
Just want to ask how to solve this error?
p.S)my php version is php5.0.1