• java导出功能(多个sheet页数据导出)


    java导出功能(多个sheet页数据导出)



    前言

    大概内容:

    自定义格式的标题,及对应的数据,每个sheet页的表头及数据都可以不同,具体根据实际业务去变更,可以仿照这个例子去编写,这里提供的是最基础的多sheet页导出,如果需要多行表头复杂业务的多sheet页导出可参考我另一篇复杂表头,多行表头导出,如果导出不确定行数列数跟随业务的增长而变动的导出参考另一篇不确定行数列数数据的工具类

    2023.3.29补充
    上面两个链接老是失效,在我主页搜索对应的名称就能找到


    提示:以下是导出到本地,工具类也有导出到浏览器的封装方法,可直接使用
    提示:以下是导出到本地,工具类也有导出到浏览器的封装方法,可直接使用
    提示:以下是导出到本地,工具类也有导出到浏览器的封装方法,可直接使用

    一、实现的效果

    本篇测试数据为两个sheet页的导出功能,测试中导出到本地,工具类有导出到浏览器的封装方法,可直接使用

    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述

    二、调用工具类

    业务层调用

    	//假设这是需要导出的数据
    
        public static void main(String[] args) {
            /** 第一页数据 */
            List<String[]> dataAllOne = new ArrayList<>();
            String[] data1 = (String[]) Arrays.asList("杨1", "18", "男").toArray();
            String[] data2 = (String[]) Arrays.asList("杨2", "19", "女").toArray();
            dataAllOne.add(data1);
            dataAllOne.add(data2);
            /** 第二页数据 */
            List<String[]> dataAllTwo = new ArrayList<>();
            String[] data3 = (String[]) Arrays.asList("驾照", "2022年9月5日10:08:46", "是").toArray();
            String[] data4 = (String[]) Arrays.asList("户口本", "2022-9-5 10:09:01", "否").toArray();
            dataAllTwo.add(data3);
            dataAllTwo.add(data4);
    
            ArrayList<ExcelExp> list = new ArrayList<>();
            ExcelExp excelExp1 = new ExcelExp("存放人员信息", (String[]) Arrays.asList("姓名", "年龄", "性别").toArray(), dataAllOne, "人员信息");
            ExcelExp excelExp2 = new ExcelExp("存放文件信息", (String[]) Arrays.asList("文件名称", "上传时间", "是否上传到FDFS").toArray(), dataAllTwo, "文件上传情况");
            list.add(excelExp1);
            list.add(excelExp2);
            Workbook workbook = ExcelExportUtil.exportManySheetExcel(list);
    
            //导出数据到excel
            FileOutputStream fileOutputStream = null;
            try {
                fileOutputStream = new FileOutputStream("F:/新建文件夹/demo.xls");
                workbook.write(fileOutputStream);
                fileOutputStream.flush();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if(fileOutputStream != null){
                    try {
                        fileOutputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
    
        }
    
    • 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

    三、详细工具类

    直接copy改吧改吧就可以使用,有详细注释

    import org.apache.poi.hssf.usermodel.*;
    import org.apache.poi.ss.usermodel.HorizontalAlignment;
    import org.apache.poi.ss.usermodel.Workbook;
    import org.apache.poi.ss.util.CellRangeAddress;
    
    import javax.servlet.ServletOutputStream;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.*;
    import java.net.URLEncoder;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    import java.util.Map;
    
    /**
    * @Description: java导出功能(多个sheet页数据导出)
    *
    * @Author: 杨永卓
    * @Date: 2022/9/5 10:31
    */
    public final class ExcelExportUtil {
    
        private ExcelExportUtil (){}
        private static ExcelExportUtil excelExportUtil = null;
        static{
            /** 类加载时创建,只会创建一个对象 */
            if(excelExportUtil == null) excelExportUtil = new ExcelExportUtil ();
        }
    
        /**
         * @param @param file 导出文件路径
         * @param @param mysheets
         * @return void
         * @throws
         * @Title: exportManySheetExcel
         * @Description: 可生成单个、多个sheet
         */
        public static Workbook exportManySheetExcel(List<ExcelExp> mysheets) {
    
            HSSFWorkbook wb = new HSSFWorkbook();// 创建工作薄
            List<ExcelExp> sheets = mysheets;
    
            // 表头样式
            HSSFCellStyle style = wb.createCellStyle();
            style.setAlignment(HorizontalAlignment.CENTER); // 创建一个居中格式
            // 字体样式
            HSSFFont fontStyle = wb.createFont();
            fontStyle.setFontName("微软雅黑");
            fontStyle.setFontHeightInPoints((short) 12);
            // fontStyle.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
            style.setFont(fontStyle);
    
            for (ExcelExp excel : sheets) {
                // 新建一个sheet
                HSSFSheet sheet = wb.createSheet(excel.getFileName());// 获取该sheet名称
    
                String[] handers = excel.getHanders();// 获取sheet的标题名
    
                HSSFRow tableName = sheet.createRow(0);
                HSSFCell cellName = tableName.createCell(0);
                sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 9));
                HSSFCellStyle titleStyle = wb.createCellStyle();
                // 设置单元格样式
                HSSFFont titleFont = wb.createFont(); // 标题字体
                titleFont.setFontHeightInPoints((short) 16); // 字号
                titleStyle.setFont(titleFont);
                titleStyle.setAlignment(HorizontalAlignment.CENTER);
    
                cellName.setCellStyle(titleStyle);
                // 设置单元格内容
                cellName.setCellValue(excel.getTableName());
    
                HSSFRow rowFirst = sheet.createRow(1);// 第一个sheet的第一行为标题
                // 写标题
                for (int i = 0; i < handers.length; i++) {
                    // 获取第一行的每个单元格
                    HSSFCell cell = rowFirst.createCell(i);
                    // 往单元格里写数据
                    cell.setCellValue(handers[i]);
                    cell.setCellStyle(style); // 加样式
                    sheet.setColumnWidth(i, 4000); // 设置每列的列宽
                }
    
                // 写数据集
                List<String[]> dataset = excel.getDataset();
                for (int i = 0; i < dataset.size(); i++) {
                    String[] data = dataset.get(i);// 获取该对象
    
                    // 创建数据行
                    HSSFRow row = sheet.createRow(i + 2);
    
                    for (int j = 0; j < data.length; j++) {
                        // 设置对应单元格的值
                        row.createCell(j).setCellValue(data[j]);
                    }
                }
            }
            return wb;
        }
    
        /**
         * @Description: [方法1:导出到浏览器]
         * @Param: [fileName, wb, response]
         * @return: void
         * @Author: yangyongzhuo
         * @Date: 2022/7/25 9:40
         */
        private static void buildExcelDocument(String fileName, Workbook wb, HttpServletResponse response) {
            try {
                response.setContentType("application/octet-stream");
                // 可自行定义编码格式
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
                // 清除jsp编译html文件的空白,防止excel出现空行
                response.flushBuffer();
                // 写出
                wb.write(response.getOutputStream());
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                IOUtils.closeQuietly(wb);
            }
        }
    
        /**
         * @Description: [方法2:导出到浏览器]
         * @Param: [fileName, wb, response,request]
         * @return: void
         * @Author: yangyongzhuo
         * @Date: 2022/7/25 9:40
         */
        public static void outputXls(Workbook workbook, String fileName, HttpServletResponse response,
                                     HttpServletRequest request) {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
    
            try {
                workbook.write(os);
                byte[] content = os.toByteArray();
                InputStream is = new ByteArrayInputStream(content);
                // 设置response参数,可以打开下载页面
                response.reset();
                response.setContentType("application/vnd.ms-excel;charset=utf-8");
                response.setHeader("Content-Disposition",
                        "attachment;filename=" + encodeFileName(fileName + ".xls", request));
                ServletOutputStream out = response.getOutputStream();
                BufferedInputStream bis = null;
                BufferedOutputStream bos = null;
                try {
                    bis = new BufferedInputStream(is);
                    bos = new BufferedOutputStream(out);
                    byte[] buff = new byte[2048];
                    int bytesRead;
                    // Simple read/write loop.
                    while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                        bos.write(buff, 0, bytesRead);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null)
                        bis.close();
                    if (bos != null)
                        bos.close();
                }
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    
        public static String encodeFileName(String fileName, HttpServletRequest request)
                throws UnsupportedEncodingException {
            String agent = request.getHeader("USER-AGENT");
            if (null != agent && -1 != agent.indexOf("MSIE")) {
                return URLEncoder.encode(fileName, "UTF-8");
            } else if (null != agent && -1 != agent.indexOf("Mozilla")) {
                return "=?UTF-8?B?"
                        + (new String(org.apache.commons.codec.binary.Base64.encodeBase64(fileName.getBytes("UTF-8")))) + "?=";
            } else {
                return fileName;
            }
        }
    
        /**
         * 把list封装成list 由于我的结果集是List>,所以我写了这个个方法,把它转换成List
         *
         * @param list   要封装的list
         * @param strKey String[]的长度
         * @return
         */
        public static List<String[]> listUtils(List<Map<String, Object>> list, String[] strKey) {
    
            if (list != null && list.size() > 0) {// 如果list有值
    
                List<String[]> strList = new ArrayList<String[]>();// 实例化一个list
    
                for (Map<String, Object> map : list) {// 遍历数组
    
                    String[] str = new String[strKey.length];// 实力一个string[]
    
                    Integer count = 0;// 作为str的下标,每次从0开始
    
                    for (String s : strKey) {// 遍历map中的key
                        if (map.get(s) != null) {
                            str[count] = map.get(s).toString();
                        } else {
                            str[count] = "";
                        }
                        // 把map的value赋值到str数组中
                        count++;// str的下标+1
                    }
    
                    if (str != null) {// 如果str有值,添加到strList
                        strList.add(str);
                    }
                }
                if (strList != null && strList.size() > 0) {// 如果strList有值,返回strList
                    return strList;
                }
            }
    
            return null;
        }
        
        /**
        * @Description: 导出对象
        *
        * @Author: 杨永卓
        * @Date: 2022/9/5 10:34
        */
        private static class ExcelExp {
            private String fileName;// sheet的名称
            private String[] handers;// sheet里的标题
            private List<String[]> dataset;// sheet里的数据集
            private String tableName;
    
            public ExcelExp(String fileName, String[] handers, List<String[]> dataset, String tableName) {
                this.fileName = fileName;
                this.handers = handers;
                this.dataset = dataset;
                this.tableName = tableName;
            }
    
            public String getFileName() {
                return fileName;
            }
    
            public void setFileName(String fileName) {
                this.fileName = fileName;
            }
    
            public String[] getHanders() {
                return handers;
            }
    
            public void setHanders(String[] handers) {
                this.handers = handers;
            }
    
            public List<String[]> getDataset() {
                return dataset;
            }
    
            public void setDataset(List<String[]> dataset) {
                this.dataset = dataset;
            }
    
            public String getTableName() {
                return tableName;
            }
    
            public void setTableName(String tableName) {
                this.tableName = tableName;
            }
        }
    
    }
    
    
    • 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
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227
    • 228
    • 229
    • 230
    • 231
    • 232
    • 233
    • 234
    • 235
    • 236
    • 237
    • 238
    • 239
    • 240
    • 241
    • 242
    • 243
    • 244
    • 245
    • 246
    • 247
    • 248
    • 249
    • 250
    • 251
    • 252
    • 253
    • 254
    • 255
    • 256
    • 257
    • 258
    • 259
    • 260
    • 261
    • 262
    • 263
    • 264
    • 265
    • 266
    • 267
    • 268
    • 269
    • 270
    • 271
    • 272
    • 273
    • 274
    • 275
    • 276
    • 277

    仰天大笑出门去,我辈岂是蓬蒿人

  • 相关阅读:
    【SAP-FI】留存收益科目
    力扣刷题日志-Day2 (力扣151、43、14)
    WebRTC ULPFEC
    C++中extern的使用
    vue3项目使用TypeIt打字机
    计算机组成原理考研笔记
    看完这篇 教你玩转渗透测试靶机vulnhub——FunBox4(CTF)
    平均风向风速计算(单位矢量法)
    MySQL时间差函数 TimeStampDiff 怎么用
    MuleSoft Certified Integration Architect - Level 1 Practice Exam
  • 原文地址:https://blog.csdn.net/weixin_48207312/article/details/126699453