POI--Excel

426 阅读3分钟

一、什么是POI

在企业级应用开发中,Excel报表是一种最常见的报表需求。Excel报表开发一般分为两种形式:

  • 为了方便操作,基于Excel的报表批量上传数据

  • 通过java代码生成Excel报表。

POI提供API给Java程序对Microsoft Office格式档案读和写的功能,Apache POI是Apache软件基金会的开源项目,由Java编写的免费开源的跨平台的 Java API。

PIO有很多模块,其中包括:

  • HSSF提供读写Microsoft Excel XLS格式档案的功能。
  • XSSF提供读写Microsoft Excel OOXML XLSX格式档案的功能。
  • HWPF提供读写Microsoft Word DOC格式档案的功能。
  • HSLF提供读写Microsoft PowerPoint格式档案的功能。
  • HDGF提供读Microsoft Visio格式档案的功能。
  • HPBF提供读Microsoft Publisher格式档案的功能。
  • HSMF提供读Microsoft Outlook格式档案的功能。

二、POI--Excel入门之创建

api 说明
Workbook Excel的文档对象,针对不同的Excel类型分为:HSSFWorkbook(2003)和XSSFWorkbool(2007)
Sheet Excel的表单
Row Excel的行
Cell Excel的格子单元
font Excel字体
CellStyle 格子单元样式

创建一个maven项目,导入以下依赖

<dependencies>
    <dependency>
        <gr.poi</grooupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>4.0.1</version>
    </dependency>
    <dependency>
        <groupId>org.apacheupId>
        <artifactId>poi-ooxml</artifactId>
        <version>4.0.1</version>
    </dependency>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml-schemas</artifactId>
        <version>4.0.1</version>
    </dependency>
    <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

2.1 创建一个Excel文档

    @Test
    public  void create() throws IOException {
        //创建一个工作簿
        Workbook workbook= new XSSFWorkbook();
        //创建表单
        Sheet test = workbook.createSheet("tes");
        //创建行对象 参数的索引
        Row row = test.createRow(2);
        //创建单元格对象
        Cell cell = row.createCell(1);
        //写入内容
        cell.setCellValue("你好啊");
        //创建一个输出文件流
        FileOutputStream FileOutputStream = new FileOutputStream("src\\main\\resources\\pio\\test.xlsx");
        //写入到文件流中
        workbook.write(FileOutputStream);
    }

2.2 POI处理单元格的样式

    @Test
    public  void create() throws IOException {
        //创建一个工作簿
        Workbook workbook= new XSSFWorkbook();
        //创建表单
        Sheet test = workbook.createSheet("test");
        //创建行对象 参数的索引
        Row row = test.createRow(2);
        //创建单元格对象
        Cell cell = row.createCell(1);
        //写入内容
        cell.setCellValue("你好啊");

        //样式处理
        //创建样式对象
        CellStyle style = workbook.createCellStyle();
        //设置边宽
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setBorderBottom(BorderStyle.THIN);
        //创建字体对象
        Font font = workbook.createFont();
        font.setFontName("华文彩云");//字体
        font.setFontHeightInPoints((short)28);//字号
        style.setFont(font);
        // 行高和列宽
        row.setHeightInPoints(50);//行高
        test.setColumnWidth(2,50*256);//宽度 要*256
        //居中显示
        style.setAlignment(HorizontalAlignment.CENTER);//水平居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
        //样式设置到单元格中
        cell.setCellStyle(style);
        //创建一个输出文件流
        FileOutputStream FileOutputStream = new FileOutputStream("src\\main\\resources\\pio\\test.xlsx");
        //写入到文件流中
        workbook.write(FileOutputStream);
    }

}

2.3在Excel中添加图片

    @Test
    public  void createImg() throws IOException {
        //创建一个工作簿
        Workbook workbook= new XSSFWorkbook();
        //创建表单
        Sheet test = workbook.createSheet("test");
        //读取图片流
        FileInputStream fileInputStream = new FileInputStream("D:\\Study\\poi\\poi_demo\\src\\main\\resources\\pio\\123.jpg");
        //转化二进制数组
        byte[] bytes = IOUtils.toByteArray(fileInputStream);
        //想POI内存中添加一张图片 返回图片在图片集合的索引
        fileInputStream.read(bytes);
        int index = workbook.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);
        //绘制图片工具类
        CreationHelper helper = workbook.getCreationHelper();
        //创建一个绘图对象
        Drawing<?> drawingPatriarch = test.createDrawingPatriarch();
        //创建锚点,设置图片坐标
        ClientAnchor anchor = helper.createClientAnchor();
        anchor.setRow1(1);
        anchor.setCol1(1);
        //绘制图片 第一个是锚点,第二个是图片索引
        Picture picture = drawingPatriarch.createPicture(anchor, index);
        picture.resize();//自适应图片
        //创建一个输出文件流
        FileOutputStream FileOutputStream = new FileOutputStream("src\\main\\resources\\pio\\test.xlsx");
        //写入到文件流中
        workbook.write(FileOutputStream);
    }

三、POI--Excel入门之读取

    @Test
    public void load() throws IOException {
        //获取Excel文件创建工作部
         Workbook workbook = new XSSFWorkbook("src\\main\\resources\\pio\\demo.xlsx");
        //获取Sheet
        Sheet sheet = workbook.getSheetAt(0);
        //获取sheet中的每一行和每一个单元格 sheet.getLastRowNum()获取的是索引从0开始 所以带上=
        for (int rowNum = 0;rowNum <= sheet.getLastRowNum();rowNum++) {
            Row row = sheet.getRow(rowNum);
            StringBuilder stringBuilder = new StringBuilder();
            //row.getLastCellNum() 获取row.getLastCellNum()
            for (int cellNum = 0; cellNum < row.getLastCellNum() ; cellNum++) {
                //获取当前列
                Cell cell = row.getCell(cellNum);
                if(cell==null) continue;//如果当前为空则下一个单元格
                Object cellValue = getCellValue(cell);
                stringBuilder.append(cellValue).append("-");
            }
            System.out.println(stringBuilder.toString());
        }
    }
//获取单元格的里面的内容
    public static Object getCellValue(Cell cell){
        CellType cellType = cell.getCellType();
        Object value =null;
        switch (cellType){
            case STRING:
                value = cell.getStringCellValue();
                break;
            case BOOLEAN:
                value = cell.getBooleanCellValue();
                break;
            case NUMERIC:
                if(DateUtil.isCellDateFormatted(cell)){
                    value = cell.getDateCellValue();
                }else {
                    value = cell.getNumericCellValue();
                }
                break;
            case FORMULA://公式
                value = cell.getCellFormula();
                break;
        }
        return value;
    }