poi包简单应用

  • Post author:
  • Post category:其他


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 {

/**************创建一个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();

}

}

}