web project export excel sheet

  • Original blog address: https://blog.csdn.net/yuan487639/article/details/76212170
  • This function involves two knowledge points, one is to use excel-related plug-ins, and the other is to export files. How to configure spring-mvc
  • Let's talk about the use of the excel plug-in first. This time, the org.apache.poi package is used, and the version is 3.9. The code that can run is pasted below.
  • maven dependencies
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.9</version>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • The entity class of the plug-in can also be understood as a parameter. The build design mode is adopted here. The advantage is that some default values ​​are initialized, and the code is convenient to write when using it. For table export, I think three parameters are enough, title, header and data, so, these three parameter construction methods I designed must be passed, others use default parameters
package com.util;

import java.util.List;

public class ExcelParam {
    String name;
    int width;
    String font;
    String[] headers;
    /**
     * 导出数据的样式
     * 1:String left;
     * 2:String center
     * 3:String right
     * 4 int  right
     * 5:float ###,###.## right
     * 6:number: #.00% 百分比 right
     */
    int[] ds_format;
    /**
     * 每列表格的宽度,默认为256 * 14
     */
    int[] widths;
    List<String[]> data;

    private ExcelParam() {

    }
    //使用Builder模式,设置默认参数和必填参数
    public static class Builder {
        String name;
        int width = 256 * 14;
        String font = "微软雅黑";
        String[] headers;
        int[] ds_format;
        int[] widths;
        List<String[]> data;

        public Builder(String name) {
            this.name = name;
        }

        public Builder font(String font) {
            this.font = font;
            return this;
        }

        public Builder width(int width) {
            this.width = width;
            return this;
        }

        public Builder headers(String[] headers) {
            this.headers = headers;
            return this;
        }

        public Builder ds_format(int[] ds_format) {
            this.ds_format = ds_format;
            return this;
        }

        public Builder widths(int[] widths) {
            this.widths = widths;
            return this;
        }

        public Builder data(List<String[]> data) {
            this.data = data;
            return this;
        }

        public ExcelParam build() {
            ExcelParam excelParam = new ExcelParam();
            excelParam.name = this.name;
            excelParam.data = this.data;
            excelParam.widths = this.widths;
            excelParam.ds_format = this.ds_format;
            excelParam.headers = this.headers;
            excelParam.font = this.font;
            excelParam.width = this.width;
            return excelParam;
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • the plugin itself
package com.ucredit.util;

import org.apache.poi.hssf.usermodel.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

public class ExcelUtil {
    private ExcelUtil() {
    }

    public static void export(ExcelParam excelParam, HttpServletResponse response) throws IOException {
        if (excelParam.widths == null) {
            excelParam.widths = new int[excelParam.headers.length];
            for (int i = 0; i < excelParam.headers.length; i++) {
                excelParam.widths[i] = excelParam.width;
            }
        }
        if (excelParam.ds_format == null) {
            excelParam.ds_format = new int[excelParam.headers.length];
            for (int i = 0; i < excelParam.headers.length; i++) {
                excelParam.ds_format[i] = 1;
            }
        }
        //创建一个工作薄
        HSSFWorkbook wb = new HSSFWorkbook();
        //创建一个sheet
        HSSFSheet sheet = wb.createSheet("excel");
        int rowCount = 0;
        if (excelParam.headers != null) {
            HSSFRow row = sheet.createRow(rowCount);
            //表头样式
            HSSFCellStyle style = wb.createCellStyle();
            HSSFFont font = wb.createFont();
            font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
            font.setFontHeightInPoints((short) 11);
            style.setFont(font);
            style.setAlignment(HSSFCellStyle.ALIGN_CENTER);

            for (int i = 0; i < excelParam.headers.length; i++) {
                sheet.setColumnWidth(i, excelParam.widths[i]);
                HSSFCell cell = row.createCell(i);
                cell.setCellValue(excelParam.headers[i]);
                cell.setCellStyle(style);
            }
            rowCount++;
        }
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        //表格主体  解析list
        for (int i = 0; i < excelParam.data.size(); i++) {  //行数
            HSSFRow row = sheet.createRow(rowCount);
            for (int j = 0; j < excelParam.headers.length; j++) {  //列数
                HSSFCell cell = row.createCell(j);
                cell.setCellValue(excelParam.data.get(i)[j]);
                cell.setCellStyle(style);
            }
            rowCount++;
        }
        //设置文件名
        String fileName = excelParam.name + ".xls";
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        response.setHeader("Pragma", "No-cache");
        OutputStream outputStream = response.getOutputStream();
        wb.write(outputStream);
        outputStream.flush();
        outputStream.close();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • In fact, it can be seen from this method that the final export of the file is actually writing the file to the outputStream in the response, and the subsequent work is done by the browser.
  • controller layer writing
    @RequestMapping(value = "download")
    public void download(@RequestParam String username,
                         @RequestParam String operation_module,
                         @RequestParam String operation_type,
                         @RequestParam String start_time,
                         @RequestParam String end_time,
                         HttpServletResponse response) throws Exception {
        List<OperationLogEntity> list = operationLogDao.get(username, operation_module, operation_type, start_time, end_time);
        String[] heads = {"序号", "账号", "姓名", "操作类型", "操作模块", "处理员工号码", "处理结果", "登录IP", "时间", "所在城市"};
        List<String[]> data = new LinkedList<>();
        for (int i = 0; i < list.size(); i++) {
            OperationLogEntity entity = list.get(i);
            String[] temp = new String[10];
            temp[0] = String.valueOf(i + 1);
            temp[1] = entity.getUsername();
            temp[2] = entity.getName();
            temp[3] = entity.getOperation_type();
            temp[4] = entity.getOperation_module();
            temp[5] = entity.getProcess_number();
            temp[6] = entity.getProcess_result();
            temp[7] = entity.getIp();
            temp[8] = DateUtils.getDateBeforeOrAfterStrCN(entity.getOperation_time(), 0);
            temp[9] = entity.getCity();
            data.add(temp);
        }
        ExcelParam param = new ExcelParam.Builder("操作日志").headers(heads).data(data).build();
        ExcelUtil.export(param, response);
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • actual use
//这样写很简洁
ExcelParam param = new ExcelParam.Builder("操作日志").headers(heads).data(data).build();

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325905590&siteId=291194637