2008年11月8日 星期六

第二章 - 使用Java讀取 Excel

要使用Java讀取Excel也不難,只需要幾個步驟

1.建立要讀取Excel的路徑

2.透過Workbook.getWorkbook(File)取得Excel

3.取得Sheet

4.取得Sheet 中的 Cell

5.取得 Cell中的內容

6.關閉

 

ReadExcel.java
package tw.com.haoxiao.excel.read;

import java.io.File;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;

public class ReadExcel {
  private static String excelURL = "C:/ExcelTest.xls";
 
  public static void main(String[] args)throws Exception {
    // 宣告File指向Excel的路徑
    File excelFile = new File(excelURL);
   
    // 透過 Workbook.getWorkbook 取得Excel
    Workbook workbook = Workbook.getWorkbook(excelFile);
   
    // 取得Excel Sheet(頁籤)
    Sheet sheetByIndex = workbook.getSheet(0);
    Sheet sheetByName = workbook.getSheet("第一個頁籤");
   
    // 取得 Cell
    Cell cell1 = sheetByIndex.getCell(0, 0);
    Cell cell2 = sheetByIndex.getCell(1, 0);
    Cell cell3 = sheetByName.getCell(0, 1);
    Cell cell4 = sheetByName.getCell(1,1);
   
    // 取得 Cell的值
    String s1 = cell1.getContents();
    String s2 = cell2.getContents();
    String s3 = cell3.getContents();
    String s4 = cell4.getContents();
   
    // Print Cell Value
    System.out.println("Row 1 : " + s1 + "\t" + s2);
    System.out.println("Row 2 : " + s3 + "\t" + s4);
   
    // 關閉
    workbook.close();
  }

}

0 意見: