Apache總是讓人聯想到“優秀”這個詞。
前幾天因為某個Java系統需要用到操作Excel,于是小研究了一下POI中的HSSF,非常好用。據官網上說,Office2007格式的文檔支援也正在開發中,真是期待啊。
Apache POI包括POIFS(OLE2)、HSSF(excel)、HWPF(word)、HSLF(Powerpoint)等元件,使用者幾乎可以用它做一個簡單的Office了。
使用POI開發包時,需要先下載下傳,目前最新穩定版本是3.1。解壓後得到poi-3.1-FINAL-20080629.jar,将其加到應用的庫中即可。
下面是一段試驗代碼,可以實作建立工作薄、建立工作表、将資料填充到單元格中:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package excel;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import java.io.FileInputStream;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
/**
*
* @author Administrator
public class ExcelUtil {
public String filePath = "e:\\workbook.xls";
public void newWordBook() {
HSSFWorkbook wb = new HSSFWorkbook();
try {
FileOutputStream fileOut = new FileOutputStream(filePath);
wb.write(fileOut);
fileOut.close();
} catch (FileNotFoundException ex) {
System.out.println(ex.getMessage());
} catch (IOException ex) {
}
}
/**
* 建立空白檔案
*/
public void newSheet() {
wb.createSheet("第一頁");
wb.createSheet("第二頁");
private void saveWorkBook(HSSFWorkbook wb) {
private HSSFWorkbook getWorkBook(String filePath){
FileInputStream fileIn = new FileInputStream(filePath);
HSSFWorkbook wb = new HSSFWorkbook(fileIn);
fileIn.close();
return wb;
return null;
private HSSFCell getCell(HSSFSheet sheet,int rowIndex,short columnIndex){
HSSFRow row = sheet.getRow(rowIndex);
if (row == null) {
row = sheet.createRow(rowIndex);
HSSFCell cell = row.getCell(columnIndex);
if (cell == null) {
cell = row.createCell((short) columnIndex);
return cell;
* 寫資料
* @param file
public void writeData(String file) {
//建立工作薄
HSSFWorkbook wb = getWorkBook(file);
if(wb==null){
return;
//擷取工作表
HSSFSheet sheet = wb.getSheetAt(0);
if (sheet == null) {
sheet = wb.createSheet("第一頁");
HSSFCell cell=getCell(sheet,0,(short)0);
//數值
cell.setCellValue(123);
//字元串
HSSFRichTextString str=new HSSFRichTextString("你好");
cell=getCell(sheet,0,(short)1);
cell.setCellValue(str);
//儲存
saveWorkBook(wb);
public static void main(String[] args) {
ExcelUtil excel = new ExcelUtil();
excel.writeData(excel.filePath);
}
在JDK6上運作通過
本文轉自 王傑瑞 51CTO部落格,原文連結:http://blog.51cto.com/wangjierui/104628,如需轉載請自行聯系原作者