SpringBoot realizes POI report operation

Getting started with POI reports

In the mymes management system, operations such as personnel management and orders require the import and export of reports and other logic. The requirements are complicated, in fact, it is the basic operation of the database table. This article introduces the export of Excel, and the import of data next time

Overview of POI reports

Demand digital

In enterprise application development, Excel report is one of the most common report requirements. There are generally two ways to develop Excel reports:

  • To facilitate operation, upload data in batches based on Excel reports
  • Generate Excel report through Java code

Two forms of Excel

Currently there are two versions of Excel, Excel2003 and Excel2007 and above, the difference between the two:

SpringBoot realizes POI report operation

Common Excel operation tools:

There are two common EXCEL operation modes in Java: jxl and poi.

  • JXL can only operate on EXCEL, the structure is older, only supports Excel95-2000 version, now and stop the update and maintenance
  • POI is an apache project, which can operate on Microsoft Word, EXCEL, PPT, including office2003 and 2007, poi has been updated, all of which are more mainstream

    POI entry operation

POI environment construction


 <!--POI Excel-->
       <dependency>
           <groupId>org.apache.poi</groupId>
           <artifactId>poi</artifactId>
           <version>4.0.1</version>
       </dependency>
       <dependency>
           <groupId>org.apache.poi</groupId>
           <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>

POI structure description

  • HSSF provides xls format files for reading and writing Excel
  • XSSF provides XLSX format documents for reading and writing Excel
  • HWPF provides doc format documents for reading and writing Word
  • HSLF provides PPT format documents for reading and writing Word
  • HDGF provides to read Visio format documents
  • HSMF provides reading Outlook format documents
  • HPBF provides to read Publisher format documents

    API introduction

  • WorkBook: EXCEL document object, divided into different Excel types: HSSFWorkbook (2003) and XSSFWorkbook (2007)
  • Sheet: Excel sheet
  • Row:Excel行
  • Cell: Excel's cell grid
  • Font: Excel font
  • CellStyle: cell style

    Basic operation

Create Excel

public class PoiTest01 {
    //测试创建excel文件
    public static void main(String[] args) throws Exception {
        //1.创建workbook工作簿
        Workbook wb = new XSSFWorkbook();
        //2.创建表单Sheet
        Sheet sheet = wb.createSheet("test");
        //3.文件流
        FileOutputStream fos = new FileOutputStream("E:\\test.xlsx");
        //4.写入文件
        wb.write(fos);
        fos.close();
   }
}

Create cell

   //测试创建单元格
    public static void main(String[] args) throws Exception {
        //1.创建workbook工作簿
        Workbook wb = new XSSFWorkbook();
        //2.创建表单Sheet
        Sheet sheet = wb.createSheet("test");
        //3.创建行对象,从0开始
        Row row = sheet.createRow(3);
        //4.创建单元格,从0开始
        Cell cell = row.createCell(0);
        //5.单元格写入数据
        cell.setCellValue("传智播客");
        //6.文件流
        FileOutputStream fos = new FileOutputStream("E:\\test.xlsx");
        //7.写入文件
        wb.write(fos);
        fos.close();
   }

Formatting

   //创建单元格样式对象
        CellStyle cellStyle = wb.createCellStyle();
        //设置边框
        cellStyle.setBorderBottom(BorderStyle.DASH_DOT);//下边框
        cellStyle.setBorderTop(BorderStyle.HAIR);//上边框
        //设置字体
        Font font = wb.createFont();//创建字体对象
        font.setFontName("华文行楷");//设置字体
        font.setFontHeightInPoints((short)28);//设置字号
        cellStyle.setFont(font);
        //设置宽高
        sheet.setColumnWidth(0, 31 * 256);//设置第一列的宽度是31个字符宽度
        row.setHeightInPoints(50);//设置行的高度是50个点
        //设置居中显示
        cellStyle.setAlignment(HorizontalAlignment.CENTER);//水平居中
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
        //设置单元格样式
        cell.setCellStyle(cellStyle);
        //合并单元格
        CellRangeAddress  region =new CellRangeAddress(0, 3, 0, 2);
        sheet.addMergedRegion(region);

Insert picture

  //绘制图形
    public static void main(String[] args) throws Exception {
        //1.创建workbook工作簿
        Workbook wb = new XSSFWorkbook();
        //2.创建表单Sheet
        Sheet sheet = wb.createSheet("test");
        //读取图片流
        FileInputStream stream=new FileInputStream("e:\\logo.jpg");
        byte[] bytes= IOUtils.toByteArray(stream);
        //读取图片到二进制数组
        stream.read(bytes);
        //向Excel添加一张图片,并返回该图片在Excel中的图片集合中的下标
        int pictureIdx = wb.addPicture(bytes,Workbook.PICTURE_TYPE_JPEG);
        //绘图工具类
        CreationHelper helper = wb.getCreationHelper();
           //创建一个绘图对象
        Drawing<?> patriarch = sheet.createDrawingPatriarch();
        //创建锚点,设置图片坐标
        ClientAnchor anchor = helper.createClientAnchor();
        anchor.setCol1(0);//从0开始
        anchor.setRow1(0);//从0开始
        //创建图片
        Picture picture = patriarch.createPicture(anchor, pictureIdx);
        picture.resize();
        //6.文件流
        FileOutputStream fos = new FileOutputStream("E:\\test.xlsx");
        //7.写入文件
        wb.write(fos);
        fos.close();
   }

POI report export

No matter what the requirement is, only the export of the report requires the following steps:

  • Construct Excel table data
  • Create workbook
  • Create sheet object
  • Create Row object
  • Create Cell object
  • Data filling, setting styles and
    downloading. Take user data as an example. Those who have not spent my article can follow the official account and read the previous article

    Create FileUtil file operation general class

package com.cn.greemes.common.util;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.poi.excel.BigExcelWriter;
import cn.hutool.poi.excel.ExcelUtil;
import org.apache.poi.xssf.streaming.SXSSFSheet;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 文件操作
 */
public class FileUtil {

    public static final String SYS_TEM_DIR =System.getProperty("java.io.tmpdir")+ File.separator;

    public static void downloadExcel(List<Map<String, Object>> list, HttpServletResponse response) throws IOException {
        String tempPath = SYS_TEM_DIR + IdUtil.fastSimpleUUID() + ".xlsx";
        File file = new File(tempPath);
        BigExcelWriter writer = ExcelUtil.getBigWriter(file);
        // 一次性写出内容,使用默认样式,强制输出标题
        writer.write(list, true);
        SXSSFSheet sheet = (SXSSFSheet)writer.getSheet();
        //上面需要强转SXSSFSheet  不然没有trackAllColumnsForAutoSizing方法
        sheet.trackAllColumnsForAutoSizing();
        //列宽自适应
        writer.autoSizeColumnAll();
        //response为HttpServletResponse对象
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        //test.xls是弹出下载对话框的文件名,不能为中文,中文请自行编码
        response.setHeader("Content-Disposition", "attachment;filename=file.xlsx");
        ServletOutputStream out = response.getOutputStream();
        // 终止后删除临时文件
        file.deleteOnExit();
        writer.flush(out, true);
        //此处记得关闭输出Servlet流
        IoUtil.close(out);
    }
}

Configure in the controller

 @ApiOperation("导出用户数据")
   @RequestMapping(value = "/export", method = RequestMethod.GET)
   @ResponseBody
   public void export(HttpServletResponse response, @RequestParam(value = "keyword", required = false) String keyword,
                      @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                      @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) throws UnsupportedEncodingException, IOException {
       Page<MesAdmin> adminList = adminService.list(keyword, pageSize, pageNum);

       List<Map<String,Object>> list = new ArrayList();

       for(int i=0;i<149;i++) {
           for (MesAdmin umsAdmin : adminList.getRecords()) {
               Map<String, Object> map = new LinkedHashMap<>(6);
               map.put("姓名", umsAdmin.getUsername());
               map.put("邮箱", umsAdmin.getEmail());
               map.put("昵称", umsAdmin.getNickName());
               map.put("备注信息", umsAdmin.getNote());
               map.put("创建时间", umsAdmin.getCreateTime());
               map.put("最后登录时间", umsAdmin.getLoginTime());
               list.add(map);
           }
       }

       fileUtil.downloadExcel(list,response);
   }

Conclusion:

This time I will introduce the export of Excel, and the next time I will introduce the import of Excel. This is a summary of my work. If there is anything wrong, please be more direct and make progress together, thank you!

Github address:

github address: https://github.com/bangbangzhou/greemes/tree/master

the public

SpringBoot realizes POI report operation

Guess you like

Origin blog.51cto.com/15077535/2593726