Java - Excel导出工具类 ExcelExportUtils_弥耶达的博客-程序员秘密

Excel操作依赖

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.0.1</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.0.1</version>
</dependency>

Excel导出工具类

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;

import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Map;

@SuppressWarnings("unchecked")
public class ExcelExportUtils {
    

    private HttpServletResponse response;
    private String fileName;// 文件名
    private String fileDir;// 文件路径
    private String sheetName;// sheet名
    private String titleFontType = "Arial Unicode MS";// 表头字体
    private String titleBackColor = "C1FBEE";// 表头背景色
    private short titleFontSize = 12;// 表头字号
    private String address = "";// 添加自动筛选的列, 如 A:M
    private String contentFontType = "Arial Unicode MS";// 正文字体
    private short contentFontSize = 12;// 正文字号
    private String floatDecimal = ".00";// Float类型数据小数位
    private String doubleDecimal = ".00";// Double类型数据小数位
    private String colFormula[] = null;// 设置列的公式
    private DecimalFormat floatDecimalFormat = new DecimalFormat(floatDecimal);
    private DecimalFormat doubleDecimalFormat = new DecimalFormat(doubleDecimal);
    private SXSSFWorkbook workbook;

    public ExcelExportUtils(String fileDir, String sheetName) {
    
        this.fileDir = fileDir;
        this.sheetName = sheetName;
        workbook = new SXSSFWorkbook(1000);
    }

    public ExcelExportUtils(HttpServletResponse response, String fileName, String sheetName) {
    
        this.response = response;
        this.fileName = fileName;
        this.sheetName = sheetName;
        workbook = new SXSSFWorkbook(1000);
    }

    /**
     * 设置表头字体
     */
    public void setTitleFontType(String tileFontType) {
    
        this.titleFontType = tileFontType;
    }

    /**
     * 设置表头背景色
     */
    public void setTitleBackColor(String titleBackColor) {
    
        this.titleBackColor = titleBackColor;
    }

    /**
     * 设置表头字体大小
     */
    public void setTitleFontSize(short titleFontSize) {
    
        this.titleFontSize = titleFontSize;
    }

    /**
     * 设置表头自动筛选栏位, 如 A:AC
     */
    public void setAddress(String address) {
    
        this.address = address;
    }

    /**
     * 设置正文字体
     */
    public void setContentFontType(String contentFontType) {
    
        this.contentFontType = contentFontType;
    }

    /**
     * 设置正文字号
     */
    public void setContentFontSize(short contentFontSize) {
    
        this.contentFontSize = contentFontSize;
    }

    /**
     * 设置float类型数据小数位, 默认 0.00
     */
    public void setFloatDecimal(String floatDecimal) {
    
        this.floatDecimal = floatDecimal;
    }

    /**
     * 设置double类型数据小数位, 默认 0.00
     */
    public void setDoubleDecimal(String doubleDecimal) {
    
        this.doubleDecimal = doubleDecimal;
    }

    /**
     * 设置列的公式
     */
    public void setColFormula(String[] colFormula) {
    
        this.colFormula = colFormula;
    }

    /**
     * 导出Excel
     *
     * @param titleName   每列抬头名, 如 电话号码 | 归属地
     * @param titleColumn 对应抬头名的属性名, 如 telephone | ownership
     * @param titleSize   每列宽度
     * @param dataList    每行数据
     */
    public void exportExcel(String titleName[], String titleColumn[], int titleSize[], List dataList) {
    
        Sheet sheet = workbook.createSheet(this.sheetName);
        OutputStream os = null;
        try {
    
            if (fileDir != null) {
    // 写到文件中
                os = new FileOutputStream(fileDir);
            } else {
    // 写到输出流中
                os = response.getOutputStream();
                fileName += ".xlsx";
                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml");
                response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(this.fileName, "UTF-8"));
            }
            // 写表头
            Row titleNameRow = workbook.getSheet(sheetName).createRow(0);
            // 设置样式
            CellStyle titleStyle = workbook.createCellStyle();
            titleStyle = setFontAndBorder(titleStyle, titleFontType, titleFontSize);
            titleStyle = setColor(titleStyle, titleBackColor, (short) 9);
            for (int i = 0, len = titleName.length; i < len; i++) {
    // 编写表头
                sheet.setColumnWidth(i, titleSize[i] * 256);// 设置宽度
                Cell cell = titleNameRow.createCell(i);
                cell.setCellStyle(titleStyle);
                cell.setCellValue(titleName[i]);
            }
            // 为表头添加自动筛选
            if (StringUtils.isNotBlank(address) && !"null".equals(address)) {
    
                CellRangeAddress cra = CellRangeAddress.valueOf(address);
                sheet.setAutoFilter(cra);
            }
            // 通过反射获取数据并写入excel
            if (CollectionUtils.isNotEmpty(dataList)) {
    
                titleStyle = setFontAndBorder(titleStyle, contentFontType, contentFontSize);
                if (titleColumn.length > 0) {
    
                    for (int rowIndex = 1, size = dataList.size(); rowIndex <= size; rowIndex++) {
    // 先行
                        Object obj = dataList.get(rowIndex - 1);// 获取第rowIndex个数据对象
                        Class clazz = dataList.get(rowIndex - 1).getClass();// 数据对象实例
                        Row dataRow = workbook.getSheet(sheetName).createRow(rowIndex);
                        for (int columnIndex = 0, len = titleColumn.length; columnIndex < len; columnIndex++) {
    
//                            String title = (columnIndex & 1) == 1 ? titleColumn[1] : titleColumn[0];
                            String title = titleColumn[columnIndex].trim();
                            if (StringUtils.isNotBlank(title) && !"null".equals(title)) {
    
                                String data;
                                String returnType;
                                if (obj instanceof Map) {
    
                                    data = ((Map) obj).get(title) + "";
                                    returnType = "String";
                                } else {
    
                                    // 首字母大写
                                    String UTitle = Character.toUpperCase(title.charAt(0)) + title.substring(1, title.length());
                                    String methodName = "get" + UTitle;
                                    // 设置要执行的方法
                                    Method method = clazz.getDeclaredMethod(methodName);
                                    // 获取返回类型
                                    returnType = method.getReturnType().getName();
                                    data = method.invoke(obj) == null ? "" : method.invoke(obj).toString();
                                }
                                Cell cell = dataRow.createCell(columnIndex);
                                if (StringUtils.isNotBlank(data) && !"null".equals(data)) {
    
                                    if ("int".equals(returnType)) {
    
                                        cell.setCellValue(Integer.parseInt(data));
                                    } else if ("long".equals(returnType)) {
    
                                        cell.setCellValue(Long.parseLong(data));
                                    } else if ("float".equals(returnType)) {
    
                                        cell.setCellValue(floatDecimalFormat.format(Float.parseFloat(data)));
                                    } else if ("double".equals(returnType)) {
    
                                        cell.setCellValue(doubleDecimalFormat.format(Double.parseDouble(data)));
                                    } else {
    
                                        cell.setCellValue(data);
                                    }
                                }
                            } else {
    // 字段为空, 检查该列是否为公式
                                if (colFormula != null) {
    
                                    String sixBuf = colFormula[columnIndex].replace("@", (rowIndex + 1) + "");
                                    Cell cell = dataRow.createCell(columnIndex);
                                    cell.setCellFormula(sixBuf);
                                }
                            }
                        }
                    }
                }
            }
            workbook.write(os);
        } catch (Exception e) {
    
            e.printStackTrace();
        } finally {
    
            if (os != null) {
    
                try {
    
                    os.close();
                } catch (IOException e) {
    
                    e.printStackTrace();
                }
            }
        }

    }

    /**
     * 将16进制的颜色代码写入样式中来设置颜色
     *
     * @param style 保证style统一
     * @param color 颜色: 66FFDD
     * @param index 索引 8-64 使用时不可重复
     * @return CellStyle
     */
    private CellStyle setColor(CellStyle style, String color, short index) {
    
        if (StringUtils.isNotBlank(color) && !"null".equals(color)) {
    
            // 转为RGB码
            int r = Integer.parseInt(color.substring(0, 2), 16);// 转为16进制
            int g = Integer.parseInt(color.substring(2, 4), 16);
            int b = Integer.parseInt(color.substring(4, 6), 16);
            // 自定义cell颜色
//            HSSFPalette palette = workbook.getCustomPalette();
//            palette.setColorAtIndex(index, (byte) r, (byte) g, (byte) b);
            style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            style.setFillForegroundColor(index);
        }
        return style;
    }

    /**
     * 设置字体并添加外边框
     *
     * @param fontStyle 字体样式
     * @param fontName  字体名
     * @param fontSize  字体大小
     * @return CellStyle
     */
    private CellStyle setFontAndBorder(CellStyle fontStyle, String fontName, short fontSize) {
    
        Font font = workbook.createFont();
        font.setFontHeightInPoints(fontSize);
        font.setFontName(fontName);
//        font.setBold(true);// 加粗
        fontStyle.setFont(font);
        fontStyle.setBorderTop(BorderStyle.THIN);// 上边框
        fontStyle.setBorderBottom(BorderStyle.THIN);// 下边框
        fontStyle.setBorderLeft(BorderStyle.THIN);// 左边框
        fontStyle.setBorderRight(BorderStyle.THIN);// 右边框
        return fontStyle;
    }

}
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/ego_rainki/article/details/112298511

智能推荐

POJ-1064:网线主管 二分搜索_Ordinary_yfz的博客-程序员秘密

原题传送门题目大意有 NNN条绳子,它们的长度分别为 lil_ili​,如果从它们中切割出KKK条长度相同的绳子的话,这些绳子每条最长能有多长?答案保留到小数点后 2位解题思路白书中所谓典型的二分搜索题,左边界从0开始,右边界从所有绳子中最长的开始,每次统计(l+r)/2(l+r)/2(l+r)/2能切割出来多少绳子,注意以下事项:(1)由于要保留满足条件的最大长度,因此如果在midmi...

java 标签跳转_Java 语句标签实现goto跳转_weixin_39828715的博客-程序员秘密

0.前言尽管Java的设计者将goto作为保留字,但实际上并没有打算在语言中使用它。通常,使用goto语句被认为是一种拙劣的程序设计风格。当然,也有一些程序员认为反对goto的呼声似乎有些过分(例如,Donald Knuth就曾编著过一篇名为《Structured Programming with goto statements》的著名文章)。这篇文章说:无限制地使用goto语句确实是导致错误的根...

Category: Utilities_咔啡的博客-程序员秘密

Also in: Effects &gt; Custom | Data.clearQueue()Remove from the queue all items that have not yet been run.Also in: Effects &gt; Custom | Data.dequeue()Execute the next function on the queue for ...

BestCoder Round #92 比赛记录_san.hang的博客-程序员秘密

上午考完试后看到了晚上的BestCoder比赛,全机房都来参加感觉压力好大啊QAQ,要被虐了.7:00比赛开始了,迅速点进了T1大呼这好水啊!告诉了同桌怎么看中文题面然后就开始码码码,4分16秒AC了第一题7:05开始看第二题诶诶诶!!~~~~直接爆搜不久能过吗?交了一发爆搜上去,AC了,心里默默地说:这也**能过然后去刷Clarification,看到了里面的温馨提示....

分类Category的使用_weixin_30677073的博客-程序员秘密

声明方法在分类的接口中,只允许新增方法,不能新增变量。其语法格式如下:@interface 类名(分类名)  新增方法声明;@end如有在分类中定义变量,将出现错误"Instance variables may not be placed in categories"定义方法在分类的实现文件中,对新增的方法进行定义,其语法形式如下:@implem...

MyEclipse 设置默认编码为utf-8 Default Encoding_encodingutf-8default_Zeus的博客-程序员秘密

在使用eclipse时,我们经常会遇到这样的问题,系统自动生成的jsp模板默认是ISO-8859-1编码,当我们保存中文时,经常会出现编码错误而 无法保存的问题,即使我们在"项目Project"-->"属性Properties"里设置文本文件编码为UTF-8也无济于事,我们怎样才能改 变系统默认的编码为UTF-8呢?windows --> preferences --> General

随便推点

利用Vivado封装DCP文件基本流程_宁静致远dream的博客-程序员秘密

1.1 利用Vivado封装DCP文件基本流程1.1.1 本节目录1)本节目录;2)本节引言;3)FPGA简介;4)利用Vivado封装DCP文件基本流程;5)结束语。1.1.2 本节引言“不积跬步,无以至千里;不积小流,无以成江海。就是说:不积累一步半步的行程,就没有办法达到千里之远;不积累细小的流水,就没有办法汇成江河大海。1.1.3 FPGA简介FPGA(Field Programmable Gate Array)是在PAL、GAL等可编程器件的基础上进一步发展

美团-自定义规则引擎中间件_贾红平的博客-程序员秘密

引言2016年07月恰逢美团点评的业务进入“下半场”,需要我们在各个环节优化体验、提升效率、降低成本。技术团队需要怎么做来适应这个变化?这个问题直接影响着之后的工作思路。美团外卖的CRM业务步入成熟期,规则类需求几乎撑起了这个业务所有需求的半边天。一方面规则唯一不变的是“多变”,另一方面开发团队对“规则开发”的感受是乏味、疲惫和缺乏技术含量。如何解决规则开发的效率问题,最大化解放开发团队成为目前的...

Python groupby 分组 再求平均值 求和 agg聚合 transform不改变形状应用函数_groupby算总和 transform_正在学习中的李斌的博客-程序员秘密

一、 groupby 依据某列分组; groupby 依据多列分组; 二、应用 mean sum count std median size max min等函数聚合数据; 三、transform 不改变数据形状(相当于计算后替换原来的每一个元素)

Latex 制作表格出现以下错误 Extra alignment tab has been changed to \cr_ynpeng531的博客-程序员秘密

Latex 制作表格出现以下错误:Extra alignment tab has been changed to \cr. \endtemplate是由于列数没有对齐查看一共有几列,如果是五列,则将\begin{tabular}{cccc}中的c增加至五个:\begin{tabular}{ccccc}...

Category: Data_categroydata_咔啡的博客-程序员秘密

These methods allow us to associate arbitrary data with specific DOM elements.Also in: Effects &gt; Custom | Utilities.clearQueue()Remove from the queue all items that have not yet been run.Also i...

HTML基本标签_weixin_30289831的博客-程序员秘密

一、什么是HTML?HTML:超文本标签语言HTML:网页的源码浏览器:“解释和执行”HTML源码的工具二、HTML文档的结构 HTML文档主要包括三大部分:文档声明部分、&lt;head&gt;头部部分、&lt;body&gt;主体部分。&lt;!DOCTYPE html&gt;&lt;html&gt; &lt;head&gt; &l...