使用poi基于手动方式和模板方式导出excel

1.what?

poi是apache的一个office读写的一个开源库,eg:excel,word

2.how

  • jar包
     <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.11</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.11</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>3.11</version>
        </dependency>
  • poi基本使用步骤
  • 1. 创建工作表 workbook 工作簿
  • 2. 创建一个工作表 sheet
  • 3. 创建一个行对象 row(下标起始值为 0)
  • 4. 创建一个单元格对象 cell(下标起始值为 0)
  • 5. 给单元格设置内容
  • 6. 设置单元格的样式,设置字体和字体大小
  • 7. 保存,关闭流对象
  • 8. 下载

demo:

//1.创建工作簿 
Workbook wb = new HSSFWorkbook(); 
//2.创建工作表 Sheet
  //1.创建工作簿
        Workbook wb = new HSSFWorkbook();
        //2.创建工作表 Sheet
        Sheet sheet = wb.createSheet();
        //3.创建行对象 下标从 0 开始
        Row row = sheet.createRow(3);
        //4.创建单元格对象 从 0 记数
        Cell cell = row.createCell(3);
        //5.设置单元格内容
        cell.setCellValue("content");
        //6.设置单元格的样式
        CellStyle cellStyle = wb.createCellStyle();
        //创建字体对象
        Font font = wb.createFont();
        // 设置字体名称
        font.setFontName("宋体");
        //设置字体大小
        font.setFontHeightInPoints((short) 48);
        //样式中添加一个字体样式
        cellStyle.setFont(font);
        //给单元格添加样式
        cell.setCellStyle(cellStyle);
        //创建一个 输出流
        OutputStream os = new FileOutputStream("E:/img/abc.xls");
        //下载
        wb.write(os); 
        os.close();

这个是手动方式---需要手动设置单元格样式,对于操作excel表类设置样式很方便,但通过java代码来设置样式就显得有点吃力,所以我们一般先自己在excel表中设置好样式 做成一个模板,通过java代码读取它的样式即可,我们只操作数据即可

1.eg:这是通过excel做的样式

2.只需将该 excel导入工程,作为模板

3  其中 HSSFWorkbook(inputStream),可以传一个输入流,来货物传入的excel信息

获取模板excel的信息:(我这里是放在maven下的resources目下,也就是类路径下)

InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("excel/tOUTPRODUCT.xls");

Workbook wb = new HSSFWorkbook(inputStream);

通过工作表获取其他信息

 

猜你喜欢

转载自blog.csdn.net/qq_41975950/article/details/83662637
今日推荐