• 数据导出生成Excel附件使用POI的HSSFWorkbook对象


    比较常用的实现Java导入、导出Excel的技术有两种Jakarta POI和Java Excel。
    Jakarta POI 是一套用于访问微软格式文档的Java API。Jakarta POI有很多组件组成,其中有

    用于操作Excel格式文件的HSSF

    和用于操作Word的HWPF,

    目前用于操作Excel的HSSF比较成熟

    一、前端

    1、

    <el-button type="primary" size="medium" @click="exportExcell">数据导出</el-button>

    2、

    //数据导出
            exportExcel:function () {
                let self = this;
                self.table.pageData.pollutionIds=[];
                self.table.pageData.caseSourceIds=[];
                this.tagBoxList.forEach(function (item) {
                    if(item.type === 0 && item.value){
                        self.table.pageData.pollutionIds.push(item.value);
                    }
                });
                if (self.datetimeRange) {
                    self.table.pageData.startDate = this.datetimeRange[0];
                    self.table.pageData.endDate = this.datetimeRange[1];
                } else {
                    self.table.pageData.startDate='' ;
                    self.table.pageData.endDate='' ;
                }
    // 按钮事件直接访问接口地址,后面url传参数 window.location.href
    = appPath+"/service/xfxxx/exportExcel?ticketId="+self.ticketId + "&dataRange="+self.table.pageData.dataRange+" }

     二、java代码

    控制器(业务管理层):

       @ResponseBody
        @RequestMapping(value = "/exportExcel")
        public void exportExcel(HttpServletResponse response, XfxxxParam param, XfUser user) {
            JsonResult json = JsonResult.getSuccessResult();
            try {
                String fileName = "导出数据" + XfDateUtil.DateToString(CacheHelper.getTime(), XfDateUtil.YYYY_MM_DD) + ".xls";
                HSSFWorkbook wb = xxxService.exportExcel(param, user);
                try {
                    response.setCharacterEncoding("UTF-8");
                    response.setContentType("application/vnd.ms-excel");
                    response.setHeader("content-disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"), "ISO-8859-1") +".xls");
                    ExportExcel.setResponseHeader(response, fileName);
                    OutputStream os = response.getOutputStream();
                    wb.write(os);
                    os.flush();
                    os.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } catch (Exception e) {
                logger.error("导出数据报表时异常", e);
                json.setException(e);
            }
        }

    业务实施层:

    @Override
        public HSSFWorkbook exportxxx(XfxxxParam param, XfUser user) {
            calculatexxxCondition(param);
            List<XfxxxModel> xxxModelList = null;     
            xxxModelList = baseMapper.listxxx(param); // mapper接口mybatis交互数据库返回满足条件的数据
            
            String[] title = {"案件编号", "案件来源", "污染类型", "问题属地", "投诉对象", "问题描述", "举报时间", "要求结办时间", "状态"}; // excel的表头
            String sheetName = "案件数据";
            String[][] content = new String[xxxModelList.size()][];
            for (int i = 0; i < xxxModelList.size(); i++) {
                content[i] = new String[title.length];
                XfxxxModel xxxModel = xxxModelList.get(i);
                content[i][0] = xxxModel.getCaseCode();
                content[i][1] = xxxModel.getCaseSource();
                content[i][2] = xxxModel.getPollutionCtg();
                content[i][3] = xxxModel.getCantonName();
                content[i][4] = xxxModel.getInstName();
                content[i][5] = xxxModel.getxxxReason();
                if (Objects.nonNull(xxxModel.getTime())) {
    //                content[i][6] = XfDateUtil.DateToString(xxxModel.getTime(), XfDateUtil.YYYY_MM_DD_HHMMSS);
                    content[i][6] = XfDateUtil.DateToString(xxxModel.getTime(), XfDateUtil.YYYY_MM_DD);//带上时分秒excel解析月份会有问题(出现月份大于12的情况)
                }
                if (Objects.nonNull(xxxModel.getInputEndDate())) {
                    content[i][7] = XfDateUtil.DateToString(xxxModel.getInputEndDate(), XfDateUtil.YYYY_MM_DD);
                }
                content[i][8] = xxxModel.getBusiName();
            }
    
            //创建HSSFWorkbook
            HSSFWorkbook wb = ExportExcel.getHSSFWorkbook(sheetName, title, content, null);
            return wb;
        }

     封装的导出excel的工具类;

    package com.xxx.common.util;
    
    import org.apache.poi.hssf.usermodel.HSSFCell;
    import org.apache.poi.hssf.usermodel.HSSFCellStyle;
    import org.apache.poi.hssf.usermodel.HSSFRow;
    import org.apache.poi.hssf.usermodel.HSSFSheet;
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    
    import javax.servlet.http.HttpServletResponse;
    import java.io.UnsupportedEncodingException;
    
    public class ExportExcel {
    
        /**
         * 导出Excel
         *
         * @param sheetName sheet名称
         * @param title     标题
         * @param values    内容
         * @param wb        HSSFWorkbook对象
         * @return
         */
        public static HSSFWorkbook getHSSFWorkbook(String sheetName, String[] title, String[][] values, HSSFWorkbook wb) {
    
            // 第一步,创建一个HSSFWorkbook,对应一个Excel文件
            if (wb == null) {
                wb = new HSSFWorkbook();
            }
    
            // 第二步,在workbook中添加一个sheet,对应Excel文件中的sheet
            HSSFSheet sheet = wb.createSheet(sheetName);
    
            // 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制
            HSSFRow row = sheet.createRow(0);
    
            // 第四步,创建单元格,并设置值表头 设置表头居中
            HSSFCellStyle style = wb.createCellStyle();
            style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
    
            //声明列对象
            HSSFCell cell = null;
    
            //创建标题
            for (int i = 0; i < title.length; i++) {
                cell = row.createCell(i);
                cell.setCellValue(title[i]);
                cell.setCellStyle(style);
            }
    
            //创建内容
            for (int i = 0; i < values.length; i++) {
                row = sheet.createRow(i + 1);
                for (int j = 0; j < values[i].length; j++) {
                    //将内容按顺序赋给对应的列对象
                    row.createCell(j).setCellValue(values[i][j]);
                }
            }
            return wb;
        }
    
    
        public static void setResponseHeader(HttpServletResponse response, String fileName) {
            try {
                try {
                    fileName = new String(fileName.getBytes(), "ISO8859-1");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                response.setContentType("application/octet-stream;charset=ISO8859-1");
                response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
                response.addHeader("Pargam", "no-cache");
                response.addHeader("Cache-Control", "no-cache");
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    
    }
  • 相关阅读:
    js输出
    mysql主从同步(4)-Slave延迟状态监控
    mysql主从同步(3)-percona-toolkit工具(数据一致性监测、延迟监控)使用梳理
    【故障】MySQL主从同步故障-Slave_SQL_Running: No
    什么是bgp线路
    F5负载均衡虚拟服务器配置FTP端口访问不了
    Python 拷贝对象(深拷贝deepcopy与浅拷贝copy)
    东风本田/XR-V/2017款
    mysqldump导出数据库导入数据库
    .htaccess设置301跳转及常用技巧整理
  • 原文地址:https://www.cnblogs.com/wmqiang/p/11169571.html
Copyright © 2020-2023  润新知