The ssm framework uses poi to download files

Use poi to query data from the backend and encapsulate it into a file format and return it to the frontend for download. Here, the data queried by the backend is encapsulated into HSSF and directly returned to the frontend as a stream, and the browser will automatically recognize the file format.

Introduction to poi: Apache POI is an open source library of the Apache Software Foundation. POI provides APIs for Java programs to read and write files in Microsoft Office format.
There are several basic functions:
HSSF - provides the function of reading and writing files in Microsoft Excel format.
XSSF - Provides the ability to read and write files in Microsoft Excel OOXML format.
HWPF - Provides the ability to read and write files in Microsoft Word format.
HSLF - Provides the ability to read and write files in Microsoft PowerPoint format.
HDGF - Provides the ability to read and write files in Microsoft Visio format.
These functions can meet most of the needs, use the corresponding class to return the corresponding file format!

This is a download in excel format

  1. Import poi dependencies
<!--poi依赖-->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.15</version>
</dependency>
  1. Query the data required by the customer and encapsulate it into a collection
<select id="selectAllActivities" resultMap="BaseResultMap">
    select
    ta.id,tu1.name as owner, ta.name, ta.start_date, ta.end_date, ta.cost, ta.description, ta.create_time,tu2.name as create_by,
    ta.edit_time,tu3.name as edit_by
    from tbl_activity ta
    join tbl_user tu1 on ta.owner = tu1.id
    join tbl_user tu2 on ta.create_by = tu2.id
    left join tbl_user tu3 on ta.edit_by = tu3.id
    order by ta.create_time desc
</select>
  1. The service layer calls the mapper layer
@Autowired
ActivityMapper activityMapper;

public List<Activity> findAllActivities() {
    
    
    return activityMapper.selectAllActivities();
}
  1. The control layer queries data and encapsulates it into HSSF
/**
 1. 导出所有的市场活动
 2. @param request  请求
 3. @param response 响应
 */
@RequestMapping("/workbench/activity/exportAllActivity.do")
public void exportAllActivity(HttpServletRequest request, HttpServletResponse response) throws Exception {
    
    
    //查询所有市场活动
    List<Activity> activityList = marketingActivityService.findAllActivities();
    //创建一个excel文件对象
    HSSFWorkbook wb = new HSSFWorkbook();
    //使用文件对象创建一页对象,并为此页取名,不取名则采用默认名称
    HSSFSheet sheet = wb.createSheet("市场活动列表");
    //使用页对象创建行对象,0表示第一行,1位第二行,依次类推...
    HSSFRow row = sheet.createRow(0);//设置第一行
    //使用行对象创建列对象,0表示第一列,1位第二列,依次类推...
    HSSFCell cell = row.createCell(0);//设置第一行的第一列信息
    //第一列名称
    cell.setCellValue("所有者");
    //设置第二列及名称
    cell = row.createCell(1);
    cell.setCellValue("名称");
    //设置第三列及名称
    cell = row.createCell(2);
    cell.setCellValue("开始日期");
    //...
    cell = row.createCell(3);
    cell.setCellValue("结束日期");
    cell = row.createCell(4);
    cell.setCellValue("成本");
    cell = row.createCell(5);
    cell.setCellValue("描述");
    cell = row.createCell(6);
    cell.setCellValue("创建日期");
    cell = row.createCell(7);
    cell.setCellValue("创建者");
    cell = row.createCell(8);
    cell.setCellValue("修改日期");
    cell = row.createCell(9);
    cell.setCellValue("修改者");

    //设置列的样式
    HSSFCellStyle style = wb.createCellStyle();
    //设置为左对齐,HorizontalAlignment这是一个枚举类,可以设置多种样式
    style.setAlignment(HorizontalAlignment.LEFT);

    if (activityList != null) {
    
    
        Activity activity = null;
        //遍历集合
        for (int i = 0; i < activityList.size(); i++) {
    
    
            activity = activityList.get(i);//获取集合中的每个对象

            //设置第二行,因为上面设置了0,这里需要加1,如果将i设置为1,那第一条对象将无法取到
            row = sheet.createRow(i + 1);

            cell = row.createCell(0);//设置第i+1行的第一列信息
            cell.setCellValue(activity.getOwner());
            cell = row.createCell(1);
            cell.setCellValue(activity.getName());
            cell = row.createCell(2);
            cell.setCellValue(activity.getStartDate());
            cell = row.createCell(3);
            cell.setCellValue(activity.getEndDate());
            cell = row.createCell(4);
            cell.setCellValue(activity.getCost());
            cell = row.createCell(5);
            cell.setCellValue(activity.getDescription());
            cell = row.createCell(6);
            cell.setCellValue(activity.getCreateTime());
            cell = row.createCell(7);
            cell.setCellValue(activity.getCreateBy());
            cell = row.createCell(8);
            cell.setCellValue(activity.getEditTime());
            cell = row.createCell(9);
            cell.setCellValue(activity.getEditBy());
        }
    } 
    
    //设置响应信息类型及编码,避免乱码
    //响应类型为二进制流响应,直接以流的方式响应,任何文件都能响应到前台,也能指定类型响应
    response.setContentType("application/octet-stream;charset=UTF-8");

    //根据HTTP协议的规定,浏览器每次向服务器发送请求,都会把浏览器信息以请求头的形式发送到服务器
    String browser = request.getHeader("User-Agent");

    //不同的浏览器接收响应头采用的编码格式不一样:IE采用 urlencoded、火狐采用 ISO8859-1
    //使用URLEncoder.encode,将文字的编码设置为urlencoded
    String fileName = URLEncoder.encode("市场活动列表", "UTF-8");
    if (browser.contains("firefox")) {
    
    
        //火狐采用 ISO8859-1,将"市场活动列表"字符串以utf-8的编码方式打散
        // 再以"ISO8859-1"编码格式组合起来,字符串编码格式变为"ISO8859-1"
        fileName = new String("市场活动列表".getBytes(StandardCharsets.UTF_8), "ISO8859-1");
    }
    //可以设置响应头信息,使浏览器接收到响应信息之后,在下载窗口打开
    response.addHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");

    //获取响应输出流对象
    ServletOutputStream os = response.getOutputStream();

    //将文件输出到浏览器
    wb.write(os);
    //刷新并关闭资源
    os.flush();
    wb.close();
}

Common comparison table of response file types: https://tool.oschina.net/commons/

  1. Just send the request directly from the front desk, and the browser will recognize the response file and generate the corresponding file download
$("#exportActivityBtn").click(function () {
    
    
    //点击全部导出按钮,跳转到后台控制器,同步请求
    window.location.href = "<%=basePath%>workbench/activity/exportAllActivity.do";
});

At this point, the function of downloading excel files is completed! If you want to download files in different formats, use the class corresponding to poi to encapsulate, and you can complete the download in the download format you want

Guess you like

Origin blog.csdn.net/m0_46803792/article/details/106757855