星期四, 7月 06, 2006

POI HSSF(Read Excel)備忘記

由於最近工作需要讀取某些Excel,故將測試的過程簡單的記錄下來.

下載poi-bin-3.0-alpha2-20060616.zip
http://apache.mirrors.hoobly.com/jakarta/poi/dev/bin/


解壓縮後把下面三個 library 加入 CLASSPATH 中:
poi-3.0-alpha2-20060616.jar
poi-contrib-3.0-alpha2-20060616.jar
poi-scratchpad-3.0-alpha2-20060616.jar

account.xls 內容:
name password email
joeyta 123456 joeyta@matrix.org.cn
jane 123123 jane@matrix.org.cn

Account.java
public class Account{
private String name;
private String password;
private String email;
public String getName(){
return this.name;
}
public void setName(String name){
this.name = name;
}
public String getPassword(){
return this.password;
}
public void setPassword(String password){
this.password= password;
}
public String getEmail(){
return this.email;
}
public void setAge(String email){
this.email= email;
}
public String getClassName() {
return this.getClass().getName().substring(
this.getClass().getPackage().getName().length() + 1);
}
public String toString(){
return getClassName() + "@" this.name + "#" + this.password + "#" + this.email;
}

}

ReadAccountFromExcel.java
public class ReadAccountFromExcel {
private ArrayList accountList = new ArrayList();
private String filePath = "account.xls";
public void readExcel() throws IOException {
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(filePath));
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0); // 取得Excel第一個sheet(從0開始)
for (int i = 1; i < sheet.getLastRowNum(); i++) { // 由於第 0 Row 為 title, 故 i 從 1 開始
HSSFRow row = sheet.getRow(i); // 取得第 i Row
Account account = new Account();
account.setName(row.getCell((short)0).toString()); // 取得第1個cell (為name)
account.setPassword(row.getCell((short)1).toString()); // 取得第2個cell (為password)
account.setEmail(row.getCell((short)2).toString()); // 取得第3個cell (為email)
accountList.add(account); // 將account加入ArrayList裡
}
}

public static void main(String[] args) throws IOException {
ReadAccountFromExcel rafe = new ReadAccountFromExcel();
rafe.readExcel();

for (Iterator iter = rafe.accountList.iterator(); iter.hasNext();) { // 將所有account打印出來
Acount element = (Acount) iter.next();
System.out.println(element);
}
}
}

執行後輸出結果:
Account@joeyta#123456#joeyta@matrix.org.cn
Account@jane#123123#jane@matrix.org.cn

這裡還有更多官方的教學:
http://jakarta.apache.org/poi/hssf/quick-guide.html
http://jakarta.apache.org/poi/hssf/how-to.html

沒有留言: