一.简介
在我们进行企业的系统开发时,难免会遇到网页表格和Excel之间的操作问题(POI是个不错的选择)
Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程序对Microsoft Office格式档案读和写的功能。
基本功能:
结构:
HSSF - 提供读写Microsoft Excel格式档案的功能。
HWPF - 提供读写Microsoft Word格式档案的功能。
HSLF - 提供读写Microsoft PowerPoint格式档案的功能。
HDGF - 提供读写Microsoft Visio格式档案的功能。
二.简单代码入门实现
(注意:microsoft office提供的excel必须包含sheet表,不然文件损坏无法打开)
1.生成带sheet表的Excel
@Test
public void helloPoi()throws Exception{
Workbook wb=new HSSFWorkbook(); // 定义一个新的工作簿
wb.createSheet("第一个Sheet页"); // 创建第一个Sheet页
wb.createSheet("第二个Sheet页"); // 创建第二个Sheet页
FileOutputStream fileOut=new FileOutputStream("F:\\用Poi搞出来的工作簿.xls");
wb.write(fileOut);
fileOut.close();
}
2.sheet表中插入行和列以及数据
@Test
public void helloPoi2()throws Exception{
Workbook wb=new HSSFWorkbook(); // 定义一个新的工作簿
Sheet sheet=wb.createSheet("第一个Sheet页"); // 创建第一个Sheet页
Row row0=sheet.createRow(0); //创建一个行
row0.createCell(0).setCellValue(1); //创建单元格并赋值
row0.createCell(1).setCellValue(1.2);
row0.createCell(2).setCellValue("字符串");
row0.createCell(3).setCellValue(false);
FileOutputStream fileOut=new FileOutputStream("F:\\用Poi搞出来的工作簿1.xls");
wb.write(fileOut);
fileOut.close();
}