POI的简单使用

小编在这次实习的时候,用到了POI,一开始我人也是懵的,因为我也没用过,以为会很难,结果小编了解了之后发现其实并不难,很简单的。话不多说,直接开锤!

首先各位小伙伴可以点进去官方文档里面看一下介绍https://poi.apache.org/。POI是Apache软件基金会用Java编写的免费开源的跨平台的 Java API,主要功能是可以用Java操作Microsoft Office的相关文件。小编在工作的时候用到的是操作Excel。

使用前提:导入依赖

 1  <dependency>
 2             <groupId>org.apache.poi</groupId>
 3             <artifactId>poi</artifactId>
 4             <version>3.9</version>
 5         </dependency>
 6         <dependency>
 7             <groupId>org.apache.poi</groupId>
 8             <artifactId>poi-ooxml</artifactId>
 9             <version>3.9</version>
10         </dependency>

因为我们要用到junit测试,所以也在pom.xml里面加上junit的依赖

<dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
 </dependency>

这里我将展示最简单的使用poi创建excel文件的代码

public void testWrites() throws Exception {
        String path = "D:\\test0805\\";
        //1.创建工作簿
        Workbook workbook = new HSSFWorkbook();
        //2.创建一个工作表
        Sheet sheet = workbook.createSheet("汽车表");
        //3.创建一行
        Row row1 = sheet.createRow(0);
        //4.创建一个单元格
        Cell cell = row1.createCell(0);
        cell.setCellValue("五菱宏光");
        FileOutputStream fileOutputStream = new FileOutputStream(path + "在家测试0805.xls");
       // fileOutputStream.flush();
        workbook.write(fileOutputStream);
        fileOutputStream.flush();
        fileOutputStream.close();
        System.out.println("测试成功");
    }

创建的效果:我这里创建的excel表的路路径是D:\test0805\test0805在家测试

 

 

 

 

 

 效果如我上图所示:

①Workbook是工作薄,也就是我们创建的文件

Workbook workbook = new HSSFWorkbook();

②Sheet是工作表,上图的:"汽车表"

Sheet sheet = workbook.createSheet("汽车表");

③Row是行

 

Row row1 = sheet.createRow(0);//这里是在第0行创建的意思

④Cell是单元格

 

Cell cell = row1.createCell(0);//这里是在第0列创建一个单元格的意思

至此就创建了一个最简单的excel文件,上面顺序不可调换。

 

D:\test0805

posted @ 2020-08-05 21:45  拿着放大镜看世界  阅读(434)  评论(1)    收藏  举报