POI介绍
ApachePOI是用Java编写的免费开源的跨平台的JavaAPI,ApachePOI提供API给Java程序对MicrosoftOffice格式档案读和写的功能,其中使用最多的就是使用POI操作Excel文件。
maven坐标:
- <dependency>
- <groupId>org.apache.poi</groupId>
- <artifactId>poi</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.apache.poi</groupId>
- <artifactId>poi-ooxml</artifactId>
- </dependency>
-
POI结构:
- HSSF-提供读写MicrosoftExcelXLS格式档案的功能
- XSSF-提供读写MicrosoftExcelOOXMLXLSX格式档案的功能
- HWPF-提供读写MicrosoftWordDOC格式档案的功能
- HSLF-提供读写MicrosoftPowerPoint格式档案的功能
- HDGF-提供读MicrosoftVisio格式档案的功能
- HPBF-提供读MicrosoftPublisher格式档案的功能
- HSMF-提供读MicrosoftOutlook格式档案的功能
-
入门案例
从Excel文件读取数据
使用POI可以从一个已经存在的Excel文件中读取数据
在e盘下创建一个xlsx文件
- public class POITest {
- //使用POI读取Excel文件中的数据
- @Test
- public void test1() throws Exception{
- //加载指定文件,创建一个Excel对象(工作簿)
- XSSFWorkbook excel = new XSSFWorkbook(new FileInputStream(new File("e:\\poi.xlsx")));
- //读取Excel文件中第一个Sheet标签页
- XSSFSheet sheet = excel.getSheetAt(0);
- //遍历Sheet标签页,获得每一行数据
- for (Row row : sheet) {
- //遍历行,获得每个单元格对象
- for (Cell cell : row) {
- System.out.println(cell.getStringCellValue());
- }
- }
- //关闭资源
- excel.close();
- }
- }
-
通过上面的入门案例可以看到,POI操作Excel表格封装了几个核心对象:
XSSFWorkbook:工作簿
XSSFSheet:工作表
Row:行
Cell:单元格
上面案例是通过遍历工作表获得行,遍历行获得单元格,最终获取单元格中的值。还有一种方式就是获取工作表最后一个行号,从而根据行号获得行对象,通过行获取最后一个单元格索引,从而根据单元格索引获取每行的一个单元格对象,代码如下:
- //使用POI读取Excel文件中的数据
- @Test
- public void test2() throws Exception{
- //加载指定文件,创建一个Excel对象(工作簿)
- XSSFWorkbook excel = new XSSFWorkbook(new FileInputStream(new File("e:\\poi.xlsx")));
- //读取Excel文件中第一个Sheet标签页
- XSSFSheet sheet = excel.getSheetAt(0);
- //获得当前工作表中最后一个行号,需要注意:行号从0开始
- int lastRowNum = sheet.getLastRowNum();
- System.out.println("lastRowNum = " + lastRowNum);
- for(int i=0;i<=lastRowNum;i++){
- XSSFRow row = sheet.getRow(i);//根据行号获取每一行
- //获得当前行最后一个单元格索引
- short lastCellNum = row.getLastCellNum();
- System.out.println("lastCellNum = " + lastCellNum);
- for(int j=0;j<lastCellNum;j++){
- XSSFCell cell = row.getCell(j);//根据单元格索引获得单元格对象
- System.out.println(cell.getStringCellValue());
- }
- }
- //关闭资源
- excel.close();
- }
-
运行结果:
向Excel文件写入数据
使用POI可以在内存中创建一个Excel文件并将数据写入到这个文件,最后通过输出流将内存中的Excel文件下载到磁盘
- //使用POI向Excel文件写入数据,并且通过输出流将创建的Excel文件保存到本地磁盘
- @Test
- public void test3() throws Exception{
- //在内存中创建一个Excel文件(工作簿)
- XSSFWorkbook excel = new XSSFWorkbook();
- //创建一个工作表对象,名称叫 嘤嘤嘤
- XSSFSheet sheet = excel.createSheet("嘤嘤嘤");
- //在工作表中创建行对象
- XSSFRow title = sheet.createRow(0);
- //在行中创建单元格对象
- title.createCell(0).setCellValue("姓名");
- title.createCell(1).setCellValue("地址");
- title.createCell(2).setCellValue("年龄");
-
- XSSFRow dataRow = sheet.createRow(1);
- dataRow.createCell(0).setCellValue("小明");
- dataRow.createCell(1).setCellValue("北京");
- dataRow.createCell(2).setCellValue("20");
-
- //创建一个输出流,通过输出流将内存中的Excel文件写到磁盘
- FileOutputStream out = new FileOutputStream(new File("e:\\hello.xlsx"));
- excel.write(out);
- out.flush();
- excel.close();
- }
-
测试结果: