java 导出 多sheet页

导出最终结果

结果1

结果2

结果3

1、POI 依赖

   <!-- POI依赖 -->
   <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>3.14</version>
    </dependency>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-examples</artifactId>
        <version>3.14</version>
    </dependency>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-excelant</artifactId>
        <version>3.14</version>
    </dependency>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>3.14</version>
    </dependency>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-scratchpad</artifactId>
        <version>3.14</version>
    </dependency>

2、导出工具类

import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 
 * 文件名  ExportExcelUtil
 * 描述  通用excel导出工具类
 * @auther 简陌刀丶阿吉
 * 创建日期  2018年6月6日
 */
public class ExportExcelUtil {
 /**
 * 验证整数
 */
public static final String regNum = "^[1-9]*[1-9][0-9]*$";

/**
 * 设置excel表格样式
 * @param wb
 * @return
 */
public static CellStyle setUpCellStyle(SXSSFWorkbook wb){
    // 设置除标题行以外的样式
    CellStyle styleBold = wb.createCellStyle();
    // 设置边框下边框样式
    styleBold.setBorderBottom(XSSFCellStyle.BORDER_THIN);
    styleBold.setBottomBorderColor(HSSFColor.BLACK.index);
    // 设置边框左边框样式
    styleBold.setBorderLeft(XSSFCellStyle.BORDER_THIN);
    styleBold.setLeftBorderColor(HSSFColor.BLACK.index);
    // 设置边框上边框样式
    styleBold.setBorderTop(XSSFCellStyle.BORDER_THIN);
    styleBold.setTopBorderColor(HSSFColor.BLACK.index);
    // 设置边框右边框样式
    styleBold.setBorderRight(XSSFCellStyle.BORDER_THIN);
    styleBold.setRightBorderColor(HSSFColor.BLACK.index);
    // 垂直居中
    styleBold.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
    Font font = wb.createFont();
    // 字体高度
    font.setFontHeightInPoints((short) 11);
    styleBold.setFont(font);
    // 水平布局:居中
    styleBold.setAlignment(XSSFCellStyle.ALIGN_CENTER);
    //设置文字自动换行
    styleBold.setWrapText(true);
    return styleBold;
}

/**
 * 设置excel表头样式
 * @param wb
 * @return
 */
public static CellStyle setUpTitleCellStyle(SXSSFWorkbook wb){
    // 设置标题行样式
    CellStyle headerStyle = wb.createCellStyle();
    // 设置背景色
    headerStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
    headerStyle.setFillForegroundColor(IndexedColors.ROYAL_BLUE
            .getIndex());
    // 设置边框下边框
    headerStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);
    // 设置边框左边框
    headerStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);
    // 设置边框右边框
    headerStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);
    // 设置边框上边框
    headerStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);
    // 水平居中
    headerStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
    // 垂直居中
    headerStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
    Font headerFont = wb.createFont();
    // 字体高度
    headerFont.setFontHeightInPoints((short) 12);
    headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
    headerFont.setColor(HSSFColor.WHITE.index);
    headerStyle.setFont(headerFont);
    return headerStyle;
}

/**
 *
 * @param rege 正则表达式
 * @param param 需要验证的参数
 * @return
 */
public static boolean matchs(String rege, String param) {
    Pattern pattern = Pattern.compile(rege);
    Matcher matcher = pattern.matcher(param);
    return matcher.matches();
}

/**
 *
 * @param wb excel工作区
 * @param dataList 导出的数据
 * @param sheet 对应的sheet页
 * @param lastRowNum excel模板中的数据行数,如果指定了excel模板,需要传入该参数,否则不需要
 * @param titleList  导出的列的顺序
 */
public static void writeDateToCell(SXSSFWorkbook wb, List<Map<String, Object>> dataList, SXSSFSheet sheet, int lastRowNum, List<String> titleList) {
    // 临时文件进行压缩,建议不要true,否则会影响导出时间
    wb.setCompressTempFiles(false);
    //设置cell样式
    CellStyle styleBold = setUpCellStyle(wb);
    //设置表头样式
    CellStyle headerStyle = setUpTitleCellStyle(wb);
    //存储每一列的最大列宽的键值对,列索引为key,最大列宽为值
    Map<Integer, Integer> colMap = new HashMap<>();
    // 遍历数据,创建表格
    for (short i = 0; i < dataList.size(); i++) {
        // 创建行
        Row row = sheet.createRow(lastRowNum + i);
        // 设置行高亮
        row.setHeightInPoints(20);
        // 取数据
        Map<String, Object> fileMap = dataList.get(i);
        // 遍历map,创建单元格
        if (fileMap != null && !fileMap.isEmpty()) {
            // 用于记录每行创建的单元格个数
            int colNum = 0;
            for (String key : titleList) {
                // 如果是第一行数据,创建单元格,使用标题行样式
                if (i == 0) {
                    row.createCell(colNum).setCellStyle(headerStyle);
                } else {
                    // 其他行数据,创建单元格,使用正常的行样式
                    row.createCell(colNum).setCellStyle(styleBold);
                }
                //计算长度
                String colValue = fileMap.get(key) == null ? "" : String.valueOf(fileMap.get(key));
                //如果是整数,列宽度*2
                int strLength = matchs(regNum, colValue) ? colValue.getBytes().length * 2 * 256 :  colValue.getBytes().length * 256;
                //判断该列是否已经存在,若果存在,比较当前值与colMap中值大小,不存在,将当前字符串长度和列值保存
                if(colMap.containsKey(colNum)){
                    if(strLength > colMap.get(colNum)){
                        colMap.put(colNum, strLength);
                    }
                }else{
                    colMap.put(colNum, strLength);
                }
                // 将数据写进单元格中
                row.getCell(colNum).setCellValue(colValue);
                // 单元格记录数+1
                colNum++;
            }
        }

    }
    //遍历列值数组,设置列宽
    for (Map.Entry<Integer, Integer> entry : colMap.entrySet()) {
        Integer colWidth = entry.getValue();
        if(colWidth > 255*256) {
            colWidth = 255 * 256;
        }
        sheet.setColumnWidth(entry.getKey(), colWidth);
    }
}

/**
 *
 * @param dataList 需要导出的数据(请将标题行放在第一行)
 * @param excelPath excel模板存放路径,可以不传
 * @param fileName 导出excel文件名,可以不传,默认使用当前时间为文件名
 * @param response
 */
public static void excel(List<Map<String, Object>> dataList,
                         String excelPath, String fileName, HttpServletResponse response) {
    try {
        // 声明excel文件对象
        SXSSFWorkbook wb = null;
        // 声明sheet页
        SXSSFSheet sheet = null;
        // 设置excel文件名后缀
        // 判断是否存在excel文件路径,如果存在获取excel文件,如果不存在创建excel对象
        if (excelPath != null && !excelPath.isEmpty()) {
            // 获取excel文件对象
            File excelFile = new File(excelPath);
            // 获取文件输入流
            FileInputStream io = new FileInputStream(excelFile);
            // 创建Excel文件对象
            XSSFWorkbook xssfWorkbook = new XSSFWorkbook(io);
            // 创建SXSSF文件对象,POI3.8 beta3开始支持,基于XSSF,低内存占用
            wb = new SXSSFWorkbook(xssfWorkbook, 1000);
            for(int i = 0;i < wb.getNumberOfSheets();i++){
                // 获取第一个sheet页
                sheet = wb.getSheetAt(i);
                if(i >= dataList.size()){
                    break;
                }
                Map<String, Object> dataMap = dataList.get(i);
                List<Map<String, Object>> excelData = (List<Map<String, Object>>) dataMap.get("dataList");
                int lastRowNum = dataMap.get("lastRowNum") == null ? 0 : Integer.parseInt(String.valueOf(dataMap.get("lastRowNum")));
                List<String> titleList = (List<String>) dataMap.get("titleList");
                writeDateToCell(wb, excelData, sheet, lastRowNum, titleList);
            }
        } else {
            wb = new SXSSFWorkbook(1000);
            for(int i = 0;i < dataList.size();i++){
                Map<String, Object> dataMap = dataList.get(i);
                // 创建一个sheet页
                sheet = dataMap.get("sheetName") == null ? wb.createSheet() : wb.createSheet(String.valueOf(dataMap.get("sheetName")));
                List<Map<String, Object>> excelData = (List<Map<String, Object>>) dataMap.get("dataList");
                int lastRowNum = dataMap.get("lastRowNum") == null ? 0 : Integer.parseInt(String.valueOf(dataMap.get("lastRowNum")));
                List<String> titleList = (List<String>) dataMap.get("titleList");
                writeDateToCell(wb, excelData, sheet, lastRowNum, titleList);
            }
        }
        // 判断是否存在文件名,如果没有文件名则使用获取当前时间
        if (fileName == null || fileName.isEmpty()) {
            // 设置日期格式
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            // 设置文件名
            fileName = df.format(new Date()) + ".xlsx";
            // excel 导出部分
        }
        // 转换编码格式,防止乱码
        fileName = new String(fileName.getBytes("utf-8"), "iso8859-1");
        // 去除首部空行
        response.reset();
        // 设置response header
        response.setHeader("Content-Disposition", "attachment;filename="
                + fileName);
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        // 获取输出流
        OutputStream output = response.getOutputStream();
        BufferedOutputStream bufferedOutPut = new BufferedOutputStream(
                output);
        bufferedOutPut.flush();
        // 输出文件
        wb.write(bufferedOutPut);
        // 关闭流
        bufferedOutPut.close();
        wb.close();
    } catch (IOException | EncryptedDocumentException e) {
        e.printStackTrace();
    }
  }
}

3、调用方式

    @GetMapping(value = "/exportpbxcjhpp")
public void exportPbxcjhppExcel(@RequestParam String xlid, String date, HttpServletResponse response) {     
          Map<String, Object> paramMap = new HashMap<>();

    paramMap.put(ConstantUtil.COMMON_XLID, xlid);
    paramMap.put(ConstantUtil.DATE_KEY, date);
    List<Map<String, Object>> pbyxcjhList = 查询到的结果1;
    
    List<Map<String, Object>> xcjhList = 查询到的结果2;
    
    List<Map<String, Object>> pbList = 查询到的结果3;
    // 数据整合导出
    List<Map<String, Object>> resultList = new ArrayList<>();
    // 结果1添加title
    Map<String, Object> pbyxcjhDataMap = new HashMap<>();
    pbyxcjhDataMap.put(结果1map中的KEY, “表格表头”);
    ......
    // 结果2
    Map<String, Object> pbDataMap = new HashMap<>();
    pbDataMap.put(结果2map中的KEY, “表格表头”);
    ......
    // 行车计划
    Map<String, Object> xcjhDataMap = new HashMap<>();
    xcjhDataMap.put(结果3map中的KEY, “表格表头”);
    ......
    
    // 整理数据,添加导出列
    pbyxcjhList.add(0, pbyxcjhDataMap);
    xcjhList.add(0, xcjhDataMap);
    pbList.add(0, pbDataMap);
    
    // 结果1title
    List<String> pbyxcjhTitleList = new ArrayList<>();
    pbyxcjhTitleList.add(结果1map中的key);
    ......
    Map<String, Object> pbyxcjhMap = new HashMap<>();
    pbyxcjhMap.put("titleList", pbyxcjhTitleList);
    pbyxcjhMap.put("dataList", pbyxcjhList);
    pbyxcjhMap.put("sheetName", "结果1");
    // 结果2title
    List<String> pbTitleList = new ArrayList<>();
    pbTitleList.add(结果2map中的key);
    ......
    Map<String, Object> pbMap = new HashMap<>();
    pbMap.put("titleList", pbTitleList);
    pbMap.put("dataList", pbList);
    pbMap.put("sheetName","结果2");
    // 结果3title
    List<String> xcjhTitleList = new ArrayList<>();
    xcjhTitleList.add(结果3map中的key);
        ......
    Map<String, Object> xcjhMap = new HashMap<>();
    xcjhMap.put("titleList", xcjhTitleList);
    xcjhMap.put("dataList" xcjhList);
    xcjhMap.put("sheetName", "结果3");
    resultList.add(pbyxcjhMap);
    resultList.add(pbMap);
    resultList.add(xcjhMap);
            // 调用导出工具类
    ExportExcelUtil.excel(resultList, null, null, response);
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 157,012评论 4 359
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,589评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 106,819评论 0 237
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,652评论 0 202
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 51,954评论 3 285
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,381评论 1 210
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,687评论 2 310
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,404评论 0 194
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,082评论 1 238
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,355评论 2 241
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,880评论 1 255
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,249评论 2 250
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,864评论 3 232
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,007评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,760评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,394评论 2 269
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,281评论 2 259

推荐阅读更多精彩内容

  • excel文件导出有两种,一种是以io流直接生成,一种是在本地生成一个excel文件(fileoutputStre...
    Easy的幸福阅读 987评论 2 2
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,087评论 18 139
  • Apache POI 是用Java编写的免费开源的跨平台的 Java API,Apache POI提供API给Ja...
    玩味Orz阅读 2,519评论 0 0
  • POI操作Excel Excel简介一个excel文件就是一个工作簿workbook,一个工作簿中可以创建多张工作...
    灰气球阅读 4,624评论 2 48
  • 导入Jar包:poi 和 mysql-connector-java poi下载地址:http://mirrors....
    Hi小胡阅读 2,265评论 0 8