用 PHP 讀寫 Excel 檔案

九月 18th, 2008

PHP 讀寫 Excel 的方法有很多種,例如先轉成 CSV 格式來讀,然後用特定符號去分隔欄位。但是如果遇到欄位格式不固定的 Excel 就很麻煩了,所以需要可以直接操作 excel 的方法,方便直接指定要取某欄某列的值。

如果是 Windows 系統的話可以使用 COM 元件去讀取,但缺點就是只能在 Windows 上跑,失去了跨平台性,所以也有人另外寫出可以讀寫 Excel 的類別,這次要推薦的是 PHPExcelPHPExcel 的功能非常強大,原本就支援 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 />";

}

PHP, 程式筆記 , ,

  1. 十月 26th, 2008 at 00:45 | #1

    滿特別的!

  2. Mark
    二月 3rd, 2009 at 10:57 | #2

    I was looking for the solution that how to use PHPExcel to get row and column, your article really inspired me.

    just one thing though
    $val = $sheet->getCellByColumnAndRow($j, $i)->getValue();
    shouldn't above code be like this
    $val = $sheet->getCellByColumnAndRow($column, $row)->getValue();

    thanks man

  3. 七月 28th, 2009 at 09:37 | #4

    謝謝您的分享,
    我想將這段code貼在我的筆記內方便日後查詢用,
    想徵得您的同意,
    可否在著名出處的情況下引用您的程式碼?
    謝謝您!

  4. 七月 28th, 2009 at 10:59 | #5

    @JosephPeng
    沒問題唷!
    只要有註明來源及連結都非常歡迎轉貼。

  5. 網頁設計
    八月 5th, 2009 at 17:27 | #6

    不知道你有沒有意願幫我們弄個文字連結呢?! 請連絡我~~干溫啊!!!

  6. Angel
    八月 7th, 2009 at 21:49 | #7

    謝謝分享,非常有用!

  7. 八月 11th, 2009 at 09:59 | #8

    @網頁設計
    不好意思唷~這裡只放朋友的連結。

  8. 荣华月饼
    八月 11th, 2009 at 20:54 | #9

    没想到用php读写Excel文档那么简单的,谢啦。

  9. taiwancmh
    五月 13th, 2010 at 16:48 | #10

    如果超過25欄位~譬如BA、BB、BC
    要怎麼處理呢?

  1. 九月 19th, 2008 at 14:03 | #1