XSSFWorkbook和HSSFWorkbook导出(亲测)

简介: XSSFWorkbook和HSSFWorkbook导出(亲测)

项目上这种功能很多,写了一个工具类,代码有点垃圾,大神勿喷

导入导出poi组件Excel

<dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.9</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.9</version>
        </dependency>
package com.tc.util;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.Footer;
import org.apache.poi.ss.usermodel.Header;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * 导出工具类  <p>07导出不限制行数,03有66535局限性</p>
 *
 * @author Fyg_gm
 * @since 2021-05-12 21:01:20
 */
@Component
public class ExcelUtil {
    Logger logger = LoggerFactory.getLogger(ExcelUtil.class);
    /**
     * 07 无限制导出
     *
     * @param response
     * @param list     导出的数据
     * @param filename 导出文件名
     * @param title    导出表头
     */
    public void exportMultiToDownFile(HttpServletResponse response, List<?> list, String filename, String[] title) {
        Logger logger = LoggerFactory.getLogger(ExcelUtil.class);
        filename += new SimpleDateFormat("yyyy-MM-dd").format(System.currentTimeMillis());
        //创建工作薄
        XSSFWorkbook workbook = new XSSFWorkbook();
        //创建表单
        XSSFSheet sheet = genSheet(workbook, filename);
        //创建表单样式
        Map<String, XSSFCellStyle> tableStyle = createStyle(workbook);//创建表头样式
        Map<String, XSSFCellStyle> titleStyle = createStyle(workbook);//创建标题样式
        Map<String, XSSFCellStyle> contextStyle = createStyle(workbook);//创建正文样式
        //创建Excel
        genExcel(filename, list, title, sheet, tableStyle.get("cellStyle2"), titleStyle.get("cellStyle"), contextStyle.get("cellStyle3"));
        String suffix = ".xls";
        filename += suffix;
//            最终已流的形式返回
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
            workbook.write(out);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
            logger.info(e.getMessage());
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
                logger.info(e.getMessage());
            }
        }
    }
    /**
     * 03 限制导出行数66535 有局限性
     *
     * @param response
     * @param list     导出的数据
     * @param filename 导出的文件名
     * @param title    导出的表头
     */
    public void exportToDownFile(HttpServletResponse response, List<?> list, String filename, String[] title) {
        filename += new SimpleDateFormat("yyyy-MM-dd").format(System.currentTimeMillis());
        String suffix = ".xls";
        filename += suffix;
        //创建excel表
        HSSFWorkbook workbook = new HSSFWorkbook();
        //建立sheet对象
        HSSFSheet sheet = workbook.createSheet(filename);
        //设置默认行宽
        sheet.setDefaultColumnWidth(20);
        //创建样式
        Map<String, HSSFCellStyle> style = createStyle(workbook);
        //创建表头
        HSSFRow row = sheet.createRow(0);
        row.setHeightInPoints(20);//行高
        HSSFCell cell = row.createCell(0);
        cell.setCellValue(filename);
        cell.setCellStyle(style.get("cellStyle"));
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, (title.length - 1)));
        //创建标题
        HSSFRow rowTitle = sheet.createRow(1);
        rowTitle.setHeightInPoints(20);
        HSSFCell hc;
        for (int i = 0; i < title.length; i++) {
            hc = rowTitle.createCell(i);
            hc.setCellValue(title[i]);
            //设置标题样式
            hc.setCellStyle(style.get("cellStyle2"));
        }
        //创建表格数据
        Field[] fields;
        int i = 2;
        int index = 0;//记录额外创建的sheet数量
        //数据源
        for (Object obj : list) {
            //反射获取到实体
            fields = obj.getClass().getDeclaredFields();
            HSSFRow rowBody = sheet.createRow(i);
            rowBody.setHeightInPoints(20);
            int j = 0;
            //遍历渲染表格
            for (Field f : fields) {
                f.setAccessible(true);
                Object va = null;
                try {
                    va = f.get(obj);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                if (null == va) {
                    va = "---";
                }
                //创建行数
                hc = rowBody.createCell(j);
                //赋值数据
                hc.setCellValue(va.toString());
                //设置表格样式
                hc.setCellStyle(style.get("cellStyle3"));
                j++;
            }
            i++;
        }
        //最终已流的形式返回
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
            workbook.write(out);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
            logger.info(e.getMessage());
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
                logger.info(e.getMessage());
            }
        }
    }
    //封装动态渲染excel
    public static void genExcel(String filename, List<?> list, String[] title, XSSFSheet sheet, XSSFCellStyle tableStyle, XSSFCellStyle titleStyle, XSSFCellStyle contextStyle) {
        //设置默认行宽
        sheet.setDefaultColumnWidth(20);
        //创建第一行,为标题,index从0开始
        XSSFRow row = sheet.createRow(0);
        row.setHeightInPoints(20);
        //创建一列
        XSSFCell cell = row.createCell(0);
        //标题
        cell.setCellValue(filename);
        //设置标题样式
        cell.setCellStyle(titleStyle);
        //设置标题位置
        sheet.addMergedRegion(new CellRangeAddress(
                0, //first row
                0, //last row
                0, //first column
                (title.length - 1) //last column
        ));
        //创建第二行  表头
        XSSFRow rowTitle = sheet.createRow(1);
        rowTitle.setHeightInPoints(20);
        XSSFCell xc;
        for (int i = 0; i < title.length; i++) {
            xc = rowTitle.createCell(i);
            xc.setCellValue(title[i]);
            //设置表头样式
            xc.setCellStyle(tableStyle);
        }
        //从数据库取数据填充到Excel,
        Field[] fields;
        //i从2开始计数,因为上面已经创建了 0 1行
        int i = 2;
        for (Object obj : list) {
            //反射获取到实体
            fields = obj.getClass().getDeclaredFields();
            //从第三行动态去创建
            XSSFRow rowBody = sheet.createRow(i);
            rowBody.setHeightInPoints(20);
            int j = 0;
            //遍历渲染表格
            for (Field f : fields) {
                f.setAccessible(true);
                Object va = null;
                try {
                    va = f.get(obj);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                if (null == va) {
                    va = "---";
                }
                //创建行数
                xc = rowBody.createCell(j);
                //赋值数据
                xc.setCellValue(va.toString());
                //设置表格样式
                xc.setCellStyle(contextStyle);
                j++;
            }
            i++;
        }
    }
    //设置表单,并生成表单
    public static XSSFSheet genSheet(XSSFWorkbook workbook, String sheetName) {
        //生成表单
        XSSFSheet sheet = workbook.createSheet(sheetName);
        //设置表单文本居中
        sheet.setHorizontallyCenter(true);
        sheet.setFitToPage(false);
        //打印时在底部右边显示文本页信息
        Footer footer = sheet.getFooter();
        footer.setRight("Page " + HeaderFooter.numPages() + " Of " + HeaderFooter.page());
        //打印时在头部右边显示Excel创建日期信息
        Header header = sheet.getHeader();
        header.setRight("Create Date " + HeaderFooter.date() + " " + HeaderFooter.time());
        //设置打印方式
        XSSFPrintSetup ps = sheet.getPrintSetup();
        ps.setLandscape(true); // true:横向打印,false:竖向打印 ,因为列数较多,推荐在打印时横向打印
        ps.setPaperSize(HSSFPrintSetup.A4_PAPERSIZE); //打印尺寸大小设置为A4纸大小
        return sheet;
    }
    //设置exportToDownFile样式
    public Map<String, HSSFCellStyle> createStyle(HSSFWorkbook workbook) {
        Map<String, HSSFCellStyle> map = new HashMap<>();
        //表头样式(加粗,水平居中,垂直居中)
        HSSFCellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);//水平居中
//        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
        //设置边框样式
        cellStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN); //下边框
        cellStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);//左边框
        cellStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);//上边框
        cellStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);//右边框
        HSSFFont fontStyle = workbook.createFont();
        fontStyle.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        cellStyle.setFont(fontStyle);
        //标题样式(加粗,垂直居中)
        HSSFCellStyle cellStyle2 = workbook.createCellStyle();
//        cellStyle2.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
        cellStyle2.setFont(fontStyle);
        //设置边框样式
        cellStyle2.setBorderBottom(XSSFCellStyle.BORDER_THIN); //下边框
        cellStyle2.setBorderLeft(XSSFCellStyle.BORDER_THIN);//左边框
        cellStyle2.setBorderTop(XSSFCellStyle.BORDER_THIN);//上边框
        cellStyle2.setBorderRight(XSSFCellStyle.BORDER_THIN);//右边框
        //字段样式(垂直居中)
        HSSFCellStyle cellStyle3 = workbook.createCellStyle();
        //设置边框样式
        cellStyle3.setBorderBottom(XSSFCellStyle.BORDER_THIN); //下边框
        cellStyle3.setBorderLeft(XSSFCellStyle.BORDER_THIN);//左边框
        cellStyle3.setBorderTop(XSSFCellStyle.BORDER_THIN);//上边框
        cellStyle3.setBorderRight(XSSFCellStyle.BORDER_THIN);//右边框
        map.put("cellStyle", cellStyle);
        map.put("cellStyle2", cellStyle2);
        map.put("cellStyle3", cellStyle3);
        return map;
    }
    //设置exportMultiToDownFile样式
    public Map<String, XSSFCellStyle> createStyle(XSSFWorkbook workbook) {
        Map<String, XSSFCellStyle> map = new HashMap<>();
        //表头样式(加粗,水平居中,垂直居中)
        XSSFCellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);//水平居中
//        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
        //设置边框样式
        cellStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN); //下边框
        cellStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);//左边框
        cellStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);//上边框
        cellStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);//右边框
        XSSFFont fontStyle = workbook.createFont();
        fontStyle.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        cellStyle.setFont(fontStyle);
        //标题样式(加粗,垂直居中)
        XSSFCellStyle cellStyle2 = workbook.createCellStyle();
//        cellStyle2.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
        cellStyle2.setFont(fontStyle);
        //设置边框样式
        cellStyle2.setBorderBottom(XSSFCellStyle.BORDER_THIN); //下边框
        cellStyle2.setBorderLeft(XSSFCellStyle.BORDER_THIN);//左边框
        cellStyle2.setBorderTop(XSSFCellStyle.BORDER_THIN);//上边框
        cellStyle2.setBorderRight(XSSFCellStyle.BORDER_THIN);//右边框
        //字段样式(垂直居中)
        XSSFCellStyle cellStyle3 = workbook.createCellStyle();
//        cellStyle3.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
        //设置边框样式
        cellStyle3.setBorderBottom(XSSFCellStyle.BORDER_THIN); //下边框
        cellStyle3.setBorderLeft(XSSFCellStyle.BORDER_THIN);//左边框
        cellStyle3.setBorderTop(XSSFCellStyle.BORDER_THIN);//上边框
        cellStyle3.setBorderRight(XSSFCellStyle.BORDER_THIN);//右边框
        map.put("cellStyle", cellStyle);
        map.put("cellStyle2", cellStyle2);
        map.put("cellStyle3", cellStyle3);
        return map;
    }
}
目录
相关文章
|
SQL IDE Java
datagrip2022最新版安装破解与激活教程,亲测可用
Datagrip 应该是目前最好用的一款数据库连接工具,拥有智能查询控制台,搞笑的架构导航
8072 1
|
2月前
|
存储 程序员
Typora设置 “图片自动保存到文档对应目录下” 的方法(亲测有效)
Typora设置 “图片自动保存到文档对应目录下” 的方法(亲测有效)
|
2月前
|
Java Windows Spring
IDEA中报错:因为在此系统上禁止运行脚本有关详细信息,请参阅...(图文解释 亲测已解决)
IDEA中报错:因为在此系统上禁止运行脚本有关详细信息,请参阅...(图文解释 亲测已解决)
184 0
XMind2022最新版破解激活教程,亲测可用
Xmind 是一款 全功能 的思维导图和头脑风暴软件。像大脑的瑞士军刀一般,助你理清思路,捕捉创意。
13189 1
|
11月前
下载文档【报错的小技巧】(了解一下)
下载文档【报错的小技巧】(了解一下)
36 0
|
Linux 网络安全 数据安全/隐私保护
pycharm上传更新内容至linux服务器
pycharm上传更新内容至linux服务器
248 0
|
IDE API 开发工具
Visual Studio编辑器还原项目NuGet提示某 NuGet 程序包还原失败:找不到“xxx”版本的程序包“xxx”
Visual Studio编辑器还原项目NuGet提示某 NuGet 程序包还原失败:找不到“xxx”版本的程序包“xxx”
246 0
Visual Studio编辑器还原项目NuGet提示某 NuGet 程序包还原失败:找不到“xxx”版本的程序包“xxx”
|
存储 IDE Java
从零实现“百度网盘批量重命名”工具
工具的发明能够节省体力,同时也可以减少重复劳动,软件也是工具的一种。今天要说的是,引用 IT 技术,减少大量文件重命名这种重复的劳动。
738 0
从零实现“百度网盘批量重命名”工具
2018版本webstorm注册码 http://idea.youbbs.org 亲测可用
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_34173549/article/details/80884381 http://idea.
1331 0
|
JSON 数据格式
iTerm配置导出与迁移方法
1、前言 iTerm软件的实用就不用在说了,最近迁移新工作电脑,打算把自己电脑配置好的iTerm迁移到新电脑,网上找了很久都没有找到教程,看到iTerm的profiles下有 'Copy Profile as JSON',但没有导出成文件,也没有导入配...
3537 0