Poi即poor object interface之意,是poi項目組對微軟封閉的office文件格式(接口)的稱謂!
其中提供了對word和excel的java接口,用法非常簡單,并且是完全免費的,對中文的支持也相當不錯,下面是處理excel一個簡單的實例:
package test;
import java.io.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
public class Test {
public static void main(String[] args) {
try {
/**************創(chuàng)建一個xls文檔*************/
HSSFWorkbook wb = new HSSFWorkbook();
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
HSSFSheet sheet = wb.createSheet("new sheet");
HSSFRow row = sheet.createRow((short)0);
HSSFCell cell = row.createCell((short)0);
row.createCell((short)1);
row.createCell((short)2);
row.createCell((short)3);
row.createCell((short)4);
row.createCell((short)5);
cell.setCellValue("test_write!");
wb.write(fileOut);
fileOut.close();
/*************讀取并修改xls文檔***************/
POIFSFileSystem pfs=new POIFSFileSystem(new FileInputStream("workbook.xls"));
HSSFWorkbook hwb=new HSSFWorkbook(pfs);
HSSFSheet hs=hwb.getSheetAt(0);
HSSFRow hr=hs.getRow(0);
HSSFCellStyle style=hwb.createCellStyle();
style.setAlignment(style.ALIGN_CENTER);
HSSFFont hf=hwb.createFont();
hf.setFontName("楷體_GB2312");
style.setFont(hf);
HSSFCell cl=hr.getCell((short)2);
cl.setEncoding(cl.ENCODING_UTF_16);
cl.setCellStyle(style);
cl.setCellValue("test_modify! 測試\u2014\u2014編輯!");
FileOutputStream fos=new FileOutputStream("workbook.xls");
hwb.write(fos);
fos.flush();
fos.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}