Jakarta的POI项目提供了一组操纵Windows文档的Java API,如下几个类提供了操作Excel文件的方便的途径:HSSFWorkbook、HSSFSheet、HSSFRow、HSSFCell,分别代表了Excel电子表格中的Book、Sheet、行和单元格。
你可以在下面地址下载到最新的POI工具包:
下面的代码创建一个Excel文件test.xls,并在第一行的第一格中写入一条消息:
import org.apache.poi.hssf.usermodel.*;
import java.io.FileOutputStream;
// code run against the jakarta-poi-1.5.0-FINAL-20020506.jar.
public class PoiTest {
static public void main(String[] args) throws Exception {
FileOutputStream fos = new FileOutputStream("d:\test.xls");
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet s = wb.createSheet();
wb.setSheetName(0, "first sheet");
HSSFRow row = s.createRow(0);
HSSFCell cell = row.createCell(0);
cell.setCellValue("Hello! This message is generated from POI.");
wb.write(fos);
fos.close();
}
}
读取Excel文件时,首先生存一个POIFSFileSystem对象,由POIFSFileSystem对象构造一个HSSFWorkbook,该HSSFWorkbook对象就代表了Excel文档。下面代码读取上面生成的Excel文件写入的消息字串:
POIFSFileSystem fs = null;
HSSFWorkbook wb = null;
try {
fs = new POIFSFileSystem(new FileInputStream("d:\test.xls"));
wb = new HSSFWorkbook(fs);
} catch (IOException e) {
e.printStackTrace();
}
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row = sheet.getRow(0);
HSSFCell cell = row.getCell((short) 0);
String msg = cell.getStringCellValue();
阅读(993) | 评论(0) | 转发(0) |