广告
返回顶部
首页 > 资讯 > 后端开发 > Python >SpringBoot集成POI导出Execl表格之统一工具类
  • 404
分享到

SpringBoot集成POI导出Execl表格之统一工具类

2024-04-02 19:04:59 404人浏览 泡泡鱼

Python 官方文档:入门教程 => 点击学习

摘要

最近项目需求中有需要导出Execl表格的要求,而且还是大量的数据,于是把之前的整理了一下,抽成了一个统一的工具类,需要时直接调用工具类即可,代码如下: 一、 先看下效果 二、 导入

最近项目需求中有需要导出Execl表格的要求,而且还是大量的数据,于是把之前的整理了一下,抽成了一个统一的工具类,需要时直接调用工具类即可,代码如下:

一、 先看下效果

二、 导入依赖

<properties>
        <poi.version>4.1.2</poi.version>
        <easypoi.version>3.2.0</easypoi.version>
    </properties>
 
 
        <!-- easypoi 改jar包,在单体项目没啥问题,但在微服务项目中出现问题,因此调用了下面三个,
            大家如果解决了该问题可以告知一下互相学习-->
<!--        <dependency>-->
<!--            <groupId>cn.afterturn</groupId>-->
<!--            <artifactId>easypoi-base</artifactId>-->
<!--            <version>${easypoi.version}</version>-->
<!--        </dependency>-->
        <!-- poi start -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>${poi.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>${poi.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>${poi.version}</version>
        </dependency>
        <!-- poi end -->

三、统一工具类

集成了xlsx和xls两种方式导出;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFPalette;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
 
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.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
 

public class excelExportUtil {
    private static final Logger logger = LoggerFactory.getLogger(ExcelExportUtil.class);
    //响应
    HttpServletResponse response;
    // 文件名
    private String fileName;
    //文件保存路径
    private String fileDir;
    //sheet名
    private String sheetName;
    //表头字体
    private String titleFontType = "Arial Unicode MS";
    //表头背景色
    private String titleBackColor = "C1FBEE";
    //表头字号
    private short titleFontSize = 12;
    //添加自动筛选的列 如 A:M
    private String address = "";
    //正文字体
    private String contentFontType = "Arial Unicode MS";
    //正文字号
    private short contentFontSize = 12;
    //Float类型数据小数位
    private String floatDecimal = "0.00";
    //Double类型数据小数位
    private String doubleDecimal = "0.00";
    //时间类型
    private String parsePattern = "yyyy-MM-dd HH:mm:ss";
    //设置列的公式
    private String colFormula[] = null;
    SimpleDateFormat dateFormat = new SimpleDateFormat(parsePattern);
    DecimalFormat floatDecimalFormat = new DecimalFormat(floatDecimal);
    DecimalFormat doubleDecimalFormat = new DecimalFormat(doubleDecimal);
 
    private HSSFWorkbook workbook = null;
 
    public ExcelExportUtil() {
        workbook = new HSSFWorkbook();
    }
    public ExcelExportUtil(HttpServletResponse response, String fileName, String sheetName) {
        this.fileName = fileName;
        this.response = response;
        this.sheetName = sheetName;
        workbook = new HSSFWorkbook();
    }
 
    
    public void setTitleFontType(String titleFontType) {
        this.titleFontType = titleFontType;
    }
    
    public void setTitleBackColor(String titleBackColor) {
        this.titleBackColor = titleBackColor;
    }
    
    public void setTitleFontSize(short titleFontSize) {
        this.titleFontSize = titleFontSize;
    }
    
    public void setAddress(String address) {
        this.address = address;
    }
    
    public void setContentFontType(String contentFontType) {
        this.contentFontType = contentFontType;
    }
    
    public void setContentFontSize(short contentFontSize) {
        this.contentFontSize = contentFontSize;
    }
    
    public void setDoubleDecimal(String doubleDecimal) {
        this.doubleDecimal = doubleDecimal;
    }
    
    public void setFloatDecimalFormat(DecimalFormat floatDecimalFormat) {
        this.floatDecimalFormat = floatDecimalFormat;
    }
    
    public void setColFormula(String[] colFormula) {
        this.colFormula = colFormula;
    }
 
    
    public CellStyle setColor(CellStyle style, String color, short index) {
        if ("".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((short) index, (byte) r, (byte) g, (byte) b);
 
            style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            style.setFillForegroundColor(index);
        }
        return style;
    }
 
 
    
    public CellStyle setFontAndBorder(CellStyle style, String fontName, short size) {
        HSSFFont font = workbook.createFont();
        font.setFontHeightInPoints(size);
        font.setFontName(fontName);
        font.setBold(true);
        style.setFont(font);
        style.setBorderBottom(BorderStyle.THIN); //下边框
        style.setBorderLeft(BorderStyle.THIN);//左边框
        style.setBorderTop(BorderStyle.THIN);//上边框
        style.setBorderRight(BorderStyle.THIN);//右边框
        return style;
    }
 
    
    public CellStyle setTitleNameFont(SXSSFWorkbook workbook, CellStyle style, String fontName, short size){
        XSSFFont font = (XSSFFont) workbook.createFont();
        font.setFontHeightInPoints(size);
        font.setFontName(fontName);
        font.setBold(true);
        style.setFont(font);
        return style;
    }
 
    
    public void writeBigExcel(HttpServletResponse response, String fileName, String titleColumn[],
                              String titleName[], int titleSize[], List<?> dataList) {
        try {
            SXSSFWorkbook workbook = new SXSSFWorkbook(100);
            OutputStream out = response.getOutputStream();
            String lastFileName = fileName + ".xlsx";
            response.setContentType("application/msexcel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename="
                    + URLEncoder.encode(lastFileName, "UTF-8"));
            int k = 0;
            int rowIndex;
            Sheet sheet = workbook.createSheet(fileName + (k + 1));
            //写入excel的表头
            Row titleNameRow = workbook.getSheet(fileName + (k + 1)).createRow(0);
            //设置样式
            CellStyle  titleStyle =  workbook.createCellStyle();
            titleStyle =  setTitleNameFont(workbook, titleStyle, "Arial Unicode MS", (short) 12);
            for (int i = 0; i < titleName.length; i++) {
                sheet.setColumnWidth(i, titleSize[i] * 256);    //设置宽度
                Cell cell = titleNameRow.createCell(i);
                cell.setCellStyle(titleStyle);
                cell.setCellValue(titleName[i]);
            }
            //写入到excel中
            if (dataList != null && dataList.size() > 0) {
                if (titleColumn.length > 0) {
                    for (int index = 0; index < dataList.size(); index++) {
                        //每个sheet3W条数据
                        if (index != 0 && (index) % 30000 == 0) {
                            k = k + 1;
                            sheet = workbook.createSheet(fileName + (k + 1));
                            //写入excel的表头
                            titleNameRow = workbook.getSheet(fileName + (k + 1)).createRow(0);
                            for (int i = 0; i < titleName.length; i++) {
                                sheet.setColumnWidth(i, titleSize[i] * 256);    //设置宽度
                                Cell cell = titleNameRow.createCell(i);
                                cell.setCellStyle(titleStyle);
                                cell.setCellValue(titleName[i]);
                            }
                        }
                        if (index < 30000) {
                            rowIndex = index + 1;
                        } else {
                            rowIndex = index - 30000 * ((index) / 30000) + 1;
                        }
                        Object obj = dataList.get(index);
                        Class clazz = obj.getClass();
                        Row dataRow = workbook.getSheet(fileName + (k + 1)).createRow(rowIndex);
                        for (int columnIndex = 0; columnIndex < titleColumn.length; columnIndex++) {
                            String title = titleColumn[columnIndex].trim();
                            if (!"".equals(title)) {
                                // 获取返回类型
                                String UTitle = Character.toUpperCase(title.charAt(0)) + title.substring(1, title.length()); // 使其首字母大写;
                                String methodName = "get" + UTitle;
                                Method method = clazz.getDeclaredMethod(methodName);
                                String returnType = method.getReturnType().getName();
                                Object object = method.invoke(obj);
                                String data = method.invoke(obj) == null ? "" : object.toString();
                                Cell cell = dataRow.createCell(columnIndex);
                                if (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 if (Date.class.getName().equals(returnType)) {
                                        cell.setCellValue(dateFormat.format(object));
                                    } else {
                                        cell.setCellValue(data);
                                    }
                                } else {   //字段为空 检查该列是否是公式
                                    if (colFormula != null) {
                                        String sixBuf = colFormula[columnIndex].replace("@", (rowIndex + 1) + "");
                                        cell = dataRow.createCell(columnIndex);
                                        cell.setCellFormula(sixBuf);
 
                                    }
                                }
                            }
                        }
                    }
                }else{
                    //titleColumn为空  titleName为单列的情况
                    for (int index = 0; index < dataList.size(); index++) {
                        //每个sheet3W条数据
                        if (index != 0 && (index) % 30000 == 0) {
                            k = k + 1;
                            sheet = workbook.createSheet(fileName + (k + 1));
                            //写入excel的表头
                            titleNameRow = workbook.getSheet(fileName + (k + 1)).createRow(0);
                            for (int i = 0; i < titleName.length; i++) {
                                sheet.setColumnWidth(i, titleSize[i] * 256);    //设置宽度
                                Cell cell = titleNameRow.createCell(i);
                                cell.setCellStyle(titleStyle);
                                cell.setCellValue(titleName[i]);
                            }
                        }
                        if (index < 30000) {
                            rowIndex = index + 1;
                        } else {
                            rowIndex = index - 30000 * ((index) / 30000) + 1;
                        }
                        Object obj = dataList.get(index);
                        Row dataRow = workbook.getSheet(fileName + (k + 1)).createRow(rowIndex);
                        Cell cell = dataRow.createCell(0);
                        cell.setCellValue(obj.toString());
                    }
                }
            }
            workbook.write(out);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    
    public void writeExcel(String titleColumn[], String titleName[], int titleSize[], List<?> dataList) {
        //添加Worksheet(不添加sheet时生成的xls文件打开时会报错)
        Sheet sheet = workbook.createSheet(this.sheetName);
        //新建文件
        OutputStream out = null;
        try {
            if (fileDir != null) {
                //有文件路径
                out = new FileOutputStream(fileDir);
            } else {
                //否则,直接写到输出流中
                out = response.getOutputStream();
                fileName = fileName + ".xls";
                response.setContentType("application/msexcel;charset=UTF-8");
                response.setHeader("Content-Disposition", "attachment; filename="
                        + URLEncoder.encode(fileName, "UTF-8"));
            }
 
            //写入excel的表头
            Row titleNameRow = workbook.getSheet(sheetName).createRow(0);
            //设置样式
            CellStyle titleStyle = workbook.createCellStyle();
            titleStyle = (HSSFCellStyle) setFontAndBorder(titleStyle, titleFontType, (short) titleFontSize);
            titleStyle = (HSSFCellStyle) setColor(titleStyle, titleBackColor, (short) 10);
 
            for (int i = 0; i < titleName.length; i++) {
                sheet.setColumnWidth(i, titleSize[i] * 256);    //设置宽度
                Cell cell = titleNameRow.createCell(i);
                cell.setCellStyle(titleStyle);
                cell.setCellValue(titleName[i].toString());
            }
 
            //为表头添加自动筛选
            if (!"".equals(address)) {
                CellRangeAddress c = (CellRangeAddress) CellRangeAddress.valueOf(address);
                sheet.setAutoFilter(c);
            }
 
            //通过反射获取数据并写入到excel中
            if (dataList != null && dataList.size() > 0) {
                //设置样式
                HSSFCellStyle dataStyle = workbook.createCellStyle();
                titleStyle = (HSSFCellStyle) setFontAndBorder(titleStyle, contentFontType, (short) contentFontSize);
 
                if (titleColumn.length > 0) {
                    for (int rowIndex = 1; rowIndex <= dataList.size(); rowIndex++) {
                        Object obj = dataList.get(rowIndex - 1);     //获得该对象
                        Class clsss = obj.getClass();     //获得该对对象的class实例
                        Row dataRow = workbook.getSheet(sheetName).createRow(rowIndex);
                        for (int columnIndex = 0; columnIndex < titleColumn.length; columnIndex++) {
                            String title = titleColumn[columnIndex].toString().trim();
                            if (!"".equals(title)) {  //字段不为空
                                //使首字母大写
                                String UTitle = Character.toUpperCase(title.charAt(0)) + title.substring(1, title.length()); // 使其首字母大写;
                                String methodName = "get" + UTitle;
 
                                // 设置要执行的方法
                                Method method = clsss.getDeclaredMethod(methodName);
 
                                //获取返回类型
                                String returnType = method.getReturnType().getName();
                                Object object = method.invoke(obj);
                                String data = method.invoke(obj) == null ? "" : object.toString();
                                Cell cell = dataRow.createCell(columnIndex);
                                if (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 if (Date.class.getName().equals(returnType)) {
                                        cell.setCellValue(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(object));
                                    } 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(out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    logger.debug("导出写Excel异常");
                }
            }
        }
    }
 
}

四、调用

此处我没写成static静态方法调用

@RequestMapping("/export")
public void export(HttpServletResponse response) {
        List<Object> dataList = new ArrayList<>();
        User user1 = new User("张三", 23, "男", 173);
        User user2 = new User("李四", 20, "男", 183);
        User user3 = new User("王五", 25, "男", 165);
        User user4 = new User("小花", 18, "女", 165);
        dataList.add(user1);
        dataList.add(user2);
        dataList.add(user3);
        dataList.add(user4);
        List<String> list = new ArrayList<>();
        list.add("张三");
        list.add("李四");
        list.add("王五");
        try {
            //导出xlsx格式
            ExcelExportUtil excelExport1 = new ExcelExportUtil();
            excelExport1.writeBigExcel(response, "用户信息导出数据1", new String[]{"name", "age", "sex", "height"}
                    , new String[]{"姓名", "年龄", "性别", "身高"}
                    , new int[]{30, 30, 30, 30}, dataList);
            //导出xsl格式
//            ExcelExportUtil excelExport2 = new ExcelExportUtil(response, "用户信息导出数据2", "sheet1");
//            excelExport2.writeExcel(new String[]{"name", "age", "sex", "height"}
//                    , new String[]{"姓名", "年龄", "性别", "身高"}
//                    , new int[]{30, 30, 30, 30}, dataList);
 
            //单列的导出
//            ExcelExportUtil excelExport3 = new ExcelExportUtil();
//            excelExport3.writeBigExcel(response, "测试", new String[]{}
//                    , new String[]{"报警信息"}
//                    , new int[]{30}, list);
        } catch (Exception e) {
            e.printStackTrace();
        }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程网。

--结束END--

本文标题: SpringBoot集成POI导出Execl表格之统一工具类

本文链接: https://www.lsjlt.com/news/166697.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • SpringBoot集成POI导出Execl表格之统一工具类
    最近项目需求中有需要导出Execl表格的要求,而且还是大量的数据,于是把之前的整理了一下,抽成了一个统一的工具类,需要时直接调用工具类即可,代码如下: 一、 先看下效果 二、 导入...
    99+
    2022-11-13
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作