导出Excel工具类

新到一家公司,看以前的代码,很多重复,光一个到处excel就有好几处写法,为了代码简洁高效,所以想写一个导出的工具类,话不多说,上代码
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.zijinph.core.annotation.BeanFieldAnnotation;
import com.zijinph.core.util.StringUtil;
import com.zijinph.core.util.excel.enums.ExcelVersionEnum;
import com.zijinph.core.util.time.consts.DateTimeFormat;

import lombok.extern.log4j.Log4j2;

@Log4j2
@SuppressWarnings("rawtypes") 
public class ExportExcelUtil {
    
    private ExportExcelUtil(){}
        
    static Pattern p = Pattern.compile("^//d+(//.//d+)?$");
    
    /**
     * <p>
     * 导出无头部标题行Excel <br>
     * 时间格式默认:yyyy-MM-dd hh:mm:ss <br>
     * </p>
     * 
     * @param <T>
     * @param style,style1 excel的样式自己定义,若为空则默认使用默认样式
     * @param <T> T需要为javaBean 如果需要自定义表格头部需要加BeanFieldAnnotation注解
     * 以便反射读取字段时,顺序和你表格头部一致
     * @return 因特定原因,不能直接使用HttpServletResponse输出流,只能返回byte[]字节流
     * @param title 表格标题
     * @param dataset 数据集合
     * @param out 输出流
     * @param version 2003 或者 2007,不传时默认生成2003版本
     */
    public static <T> byte[] exportExcel(String title, Collection<T> dataset, HSSFCellStyle style, String version,XSSFCellStyle style1) {
        if (StringUtils.isEmpty(version) || String.valueOf(ExcelVersionEnum.EXCEL_2003.getVersion()).equals(version.trim())) {
           return exportExcel2003(title, null, dataset, style, DateTimeFormat.Pattern.YYYY_MM_DD_HH_MM_SS);
        } else {
           return exportExcel2007(title, null, dataset, style1, DateTimeFormat.Pattern.YYYY_MM_DD_HH_MM_SS);
        }
    }

    /**
     * <p>
     * 导出带有头部标题行的Excel <br>
     * 时间格式默认:yyyy-MM-dd hh:mm:ss <br>
     * </p>
     * 
     * @param style,style1 excel的样式自己定义,若为空则默认使用默认样式
     * @param <T> T需要为javaBean 如果需要自定义表格头部需要加BeanFieldAnnotation注解
     * 以便反射读取字段时,顺序和你表格头部一致
     * @return 因特定原因,不能直接使用HttpServletResponse输出流,只能返回byte[]字节流
     * @param title 表格标题
     * @param headers 头部标题集合
     * @param dataset 数据集合
     * @param out 输出流
     * @param version 2003 或者 2007,不传时默认生成2003版本
     */
    public static <T> byte[] exportExcel(String title, String[] headers, Collection<T> dataset, HSSFCellStyle style,
        String version,XSSFCellStyle style1) {
        if (StringUtils.isBlank(version) || String.valueOf(ExcelVersionEnum.EXCEL_2003.getVersion()).equals(version.trim())) {
           return exportExcel2003(title, headers, dataset, style, DateTimeFormat.Pattern.YYYY_MM_DD_HH_MM_SS);
        } else {
           return exportExcel2007(title, headers, dataset, style1, DateTimeFormat.Pattern.YYYY_MM_DD_HH_MM_SS);
        }
    }

    /**
     * <p>
     * 通用Excel导出方法,利用反射机制遍历对象的所有字段,将数据写入Excel文件中 <br>
     * 此版本生成2007以上版本的文件 (文件后缀:xlsx)
     * </p>
     * 
     * @param title
     *        表格标题名
     * @param headers
     *        表格头部标题集合
     * @param dataset
     *        需要显示的数据集合,集合中一定要放置符合JavaBean风格的类的对象。此方法支持的
     *        JavaBean属性的数据类型有基本数据类型及String,Date
     * @param out
     *        与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中
     * @param pattern
     *        如果有时间数据,设定输出格式。默认为"yyyy-MM-dd hh:mm:ss"
     */
    public static <T> byte[] exportExcel2007(String title, String[] headers, Collection<T> dataset,
        XSSFCellStyle style, String pattern) {
        try (XSSFWorkbook workbook = new XSSFWorkbook(); ByteArrayOutputStream bout = new ByteArrayOutputStream()) {
            // 生成一个表格
            XSSFSheet sheet = workbook.createSheet(title);
            // 设置表格默认列宽度为15个字节
            sheet.setDefaultColumnWidth(20);
            // 生成一个样式
            if(null == style){
                style = workbook.createCellStyle();
                // 设置这些样式
                style.setFillForegroundColor(new XSSFColor(java.awt.Color.gray));
                style.setAlignment(HorizontalAlignment.CENTER);
                // 生成一个字体
                XSSFFont font = workbook.createFont();
                font.setFontName("宋体");
                font.setColor(new XSSFColor(java.awt.Color.BLACK));
                font.setFontHeightInPoints((short) 11);
                // 把字体应用到当前的样式
                style.setFont(font);
            }         
            // 生成并设置另一个样式
            // 产生表格标题行
            XSSFRow row = sheet.createRow(0);
            int index = 0 ;
            XSSFCell cellHeader;
            if(null != headers && headers.length > 0){
                index = 1;
                XSSFCellStyle styleHeader = workbook.createCellStyle();
                styleHeader.setFillForegroundColor(new XSSFColor(java.awt.Color.gray));
                styleHeader.setAlignment(HorizontalAlignment.CENTER);
                XSSFFont font = workbook.createFont();
                font.setFontName("宋体");
                font.setColor(new XSSFColor(java.awt.Color.BLACK));
                font.setFontHeightInPoints((short) 11);
                font.setBold(true);
                // 把字体应用到当前的样式
                styleHeader.setFont(font);
                for (int i = 0; i < headers.length; i++) {
                    cellHeader = row.createCell(i);
                    cellHeader.setCellStyle(styleHeader);
                    cellHeader.setCellValue(new XSSFRichTextString(headers[i]));
                } 
            }           
            // 遍历集合数据,产生数据行
            Iterator<T> it = dataset.iterator();        
            SimpleDateFormat sdf = new SimpleDateFormat(pattern);
            doExcel2007(sheet, style, it,sdf,index);
            workbook.write(bout);
            return bout.toByteArray();
        } catch (SecurityException e) {
            log.error("exportExcel2007 SecurityException : {}", StringUtil.getExceptionMessage(e));
        } catch (NoSuchMethodException e) {
            log.error("exportExcel2007 NoSuchMethodException : {}", StringUtil.getExceptionMessage(e));
        } catch (IllegalArgumentException e) {
            log.error("exportExcel2007 IllegalArgumentException : {}", StringUtil.getExceptionMessage(e));
        } catch (IllegalAccessException e) {
            log.error("exportExcel2007 IllegalAccessException : {}", StringUtil.getExceptionMessage(e));
        } catch (InvocationTargetException e) {
            log.error("exportExcel2007 InvocationTargetException : {}", StringUtil.getExceptionMessage(e));
        } catch (IOException e) {
            log.error("exportExcel2007 IOException : {}", StringUtil.getExceptionMessage(e));
        }
        return new byte[]{};
    }

    private static <T> int doExcel2007(XSSFSheet sheet, XSSFCellStyle style, Iterator<T> it,
        SimpleDateFormat sdf,int index) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        XSSFRow row;
        while (it.hasNext()) {            
            row = sheet.createRow(index);
            T t = it.next();
            // 利用反射,根据JavaBean属性的先后顺序,动态调用getXxx()方法得到属性值
            List<Field> fields = getOrderedField(t.getClass().getDeclaredFields());
            for (int i = 0; i < fields.size(); i++) {
                XSSFCell cell = row.createCell(i);
                cell.setCellStyle(style);
                Class tCls = t.getClass();
                Field field = fields.get(i);
                String fieldName = field.getName();
                String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
                @SuppressWarnings("unchecked")
                Method getMethod = tCls.getMethod(getMethodName, new Class[] {});
                Object value = getMethod.invoke(t);
                // 判断值的类型后进行强制类型转换
                writeDataToExcel2007(sdf, cell, value);
            }
            index++;
        }
        return index;
    }

    private static void writeDataToExcel2007(SimpleDateFormat sdf, XSSFCell cell, Object value) {
        String textValue = null;
        if (value instanceof Integer) {
            cell.setCellValue((Integer) value);
        } else if (value instanceof Float) {
            textValue = String.valueOf((Float) value);
            cell.setCellValue(textValue);
        } else if (value instanceof Double) {
            textValue = String.valueOf((Double) value);
            cell.setCellValue(textValue);
        } else if (value instanceof Long) {
            cell.setCellValue((Long) value);
        }
        if (value instanceof Boolean) {
            textValue = "是";
            if (!(Boolean) value) {
                textValue = "否";
            }
        } else if (value instanceof Date) {
            textValue = sdf.format((Date) value);
        } else {
            // 其它数据类型都当作字符串简单处理
            if (value != null) {
                textValue = value.toString();
            }
        }
        if (textValue != null) {
            Matcher matcher = p.matcher(textValue);
            if (matcher.matches()) {
                // 是数字当作double处理
                cell.setCellValue(Double.parseDouble(textValue));
            } else {
                XSSFRichTextString richString = new XSSFRichTextString(textValue);
                cell.setCellValue(richString);
            }
        }
    }
    
    /**
     * <p>
     * 通用Excel导出方法,利用反射机制遍历对象的所有字段,将数据写入Excel文件中 <br>
     * 此方法生成2003版本的excel,文件名后缀:xls <br>
     * </p>
     * 
     * @param title
     *        表格标题名
     * @param headers
     *        表格头部标题集合
     * @param dataset
     *        需要显示的数据集合,集合中一定要放置符合JavaBean风格的类的对象。此方法支持的
     *        JavaBean属性的数据类型有基本数据类型及String,Date
     * @param out
     *        与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中
     * @param pattern
     *        如果有时间数据,设定输出格式。默认为"yyyy-MM-dd hh:mm:ss"
     */
    public static <T> byte[] exportExcel2003(String title, String[] headers, Collection<T> dataset,
        HSSFCellStyle style, String pattern) {
        try (HSSFWorkbook workbook = new HSSFWorkbook(); ByteArrayOutputStream bout = new ByteArrayOutputStream();) {
            // 生成一个表格
            HSSFSheet sheet = workbook.createSheet(title);
            // 设置表格默认列宽度为15个字节
            sheet.setDefaultColumnWidth(22);
            // 生成一个样式
            if(null == style){
                style = workbook.createCellStyle();
                // 设置这些样式
                style.setAlignment(HorizontalAlignment.CENTER); 
                // 生成一个字体
                HSSFFont font = workbook.createFont();
                font.setFontName("宋体");
                font.setFontHeightInPoints((short) 11);
                // 把字体应用到当前的样式
                style.setFont(font);
            }  
            // 产生表格标题行
            HSSFRow row = sheet.createRow(0);
            HSSFCell cellHeader;
            int index = 0;
            if(null != headers && headers.length > 0){                
                index = 1;
                HSSFCellStyle styleHeader = workbook.createCellStyle();
                styleHeader.setAlignment(HorizontalAlignment.CENTER);
                HSSFFont font = workbook.createFont();
                font.setFontName("宋体");
                font.setFontHeightInPoints((short) 12);
                font.setBold(true);
                // 把字体应用到当前的样式
                styleHeader.setFont(font);
                for (int i = 0; i < headers.length; i++) {
                    cellHeader = row.createCell(i);
                    cellHeader.setCellStyle(styleHeader);
                    cellHeader.setCellValue(headers[i]);
                }
            }
            // 遍历集合数据,产生数据行
            Iterator<T> it = dataset.iterator();
            SimpleDateFormat sdf = new SimpleDateFormat(pattern);
            doExcel2003(sheet, style, it, sdf,index);
            workbook.write(bout);
            return bout.toByteArray();
        } catch (SecurityException e) {
            log.error("exportExcel2007 SecurityException : {}", StringUtil.getExceptionMessage(e));
        } catch (NoSuchMethodException e) {
            log.error("exportExcel2007 NoSuchMethodException : {}", StringUtil.getExceptionMessage(e));
        } catch (IllegalArgumentException e) {
            log.error("exportExcel2007 IllegalArgumentException : {}", StringUtil.getExceptionMessage(e));
        } catch (IllegalAccessException e) {
            log.error("exportExcel2007 IllegalAccessException : {}", StringUtil.getExceptionMessage(e));
        } catch (InvocationTargetException e) {
            log.error("exportExcel2007 InvocationTargetException : {}", StringUtil.getExceptionMessage(e));
        } catch (IOException e) {
            log.error("exportExcel2007 IOException : {}", StringUtil.getExceptionMessage(e));
        } 
        return new byte[]{};
    }

    private static <T> int doExcel2003(HSSFSheet sheet, HSSFCellStyle style, Iterator<T> it,SimpleDateFormat sdf,int index) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        HSSFRow row;
        while (it.hasNext()) {           
            row = sheet.createRow(index);
            T t = it.next();
            // 利用反射,根据JavaBean属性的先后顺序,动态调用getXxx()方法得到属性值
            List<Field> fields = getOrderedField(t.getClass().getDeclaredFields());
            for (int i = 0; i < fields.size(); i++) {
                HSSFCell cell = row.createCell(i);
                Class tCls = t.getClass();
                cell.setCellStyle(style);
                Field field = fields.get(i);
                String fieldName = field.getName();
                String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
                @SuppressWarnings("unchecked")
                Method getMethod = tCls.getMethod(getMethodName, new Class[]{});               
                Object value = getMethod.invoke(t);
                // 判断值的类型后进行强制类型转换
                writeDataToExcel2003(sdf, cell, value);
            }
            index++;
        }
        return index;
    }

    private static void writeDataToExcel2003(SimpleDateFormat sdf, HSSFCell cell, Object value) {
        String textValue = null;
        if (value instanceof Integer) {
            cell.setCellValue((Integer) value);
        } else if (value instanceof Float) {
            textValue = String.valueOf((Float) value);
            cell.setCellValue(textValue);
        } else if (value instanceof Double) {
            textValue = String.valueOf((Double) value);
            cell.setCellValue(textValue);
        } else if (value instanceof Long) {
            cell.setCellValue((Long) value);
        }
        if (value instanceof Boolean) {
            textValue = "是";
            if (!(Boolean) value) {
                textValue = "否";
            }
        } else if (value instanceof Date) {
            textValue = sdf.format((Date) value);
        } else {
            // 其它数据类型都当作字符串简单处理
            if (value != null) {
                textValue = value.toString();
            }
        }
        if (textValue != null) {
            Matcher matcher = p.matcher(textValue);
            if (matcher.matches()) {
                // 是数字当作double处理
                cell.setCellValue(Double.parseDouble(textValue));
            } else {
                HSSFRichTextString richString = new HSSFRichTextString(textValue);
                cell.setCellValue(richString);
            }
        }
    }
    
    //排序Bean字段属性书序,前提加了BeanFieldAnnotation注解,已便和excel标题对应
    private static List<Field> getOrderedField(Field[] fields){
        List<Field> fieldList = new ArrayList<>();
        for(Field f:fields){
            if(f.getAnnotation(BeanFieldAnnotation.class)!=null){
                fieldList.add(f);
            }
        }
        fieldList.sort(Comparator.comparingInt(
                m -> m.getAnnotation(BeanFieldAnnotation.class).order()
                ));
        return fieldList;
    }

}

如果你需要设置表头标题,就要保证在写excel数据时顺序和javaBean属性顺序一致,但是 在JDK的API文档里明确标注了:不能保证getDeclaredFields()/getDeclaredMethods()返回的Fields[] 和 Methods[] 的顺序。注意是不能保证返回顺序,而不是返回是乱序:它完全可能是乱序,也还可能是按照声明顺序排布(JVM有权在编译时,自行决定类成员的顺序,不一定要按照代码中的声明顺序来进行编译。因此返回的顺序其实是class文件中的成员正向顺序,只不过在编译时这个顺序不一定等于声明时的顺序),所以,需要自定义一个注解来设置Bean的顺序以保证数据和标题一致性。

package com.zijinph.core.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
  * @author hankailin
  * @version 2018年10月24日 下午3:17:01
  * 此注解对导出excel中反射去字段顺序做支撑
  */


@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface BeanFieldAnnotation {
    
    int order();
    
}

javaBean:
package com.rain.contral;

public class Demo {

    @BeanFieldAnnotation(order = 1)
    private String name;

    @BeanFieldAnnotation(order = 2)
    private String address;

    @BeanFieldAnnotation(order = 3)
    private String cardId;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getCardId() {
        return cardId;
    }

    public void setCardId(String cardId) {
        this.cardId = cardId;
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SpringBoot导出Excel工具类可以使用EasyExcel库来实现。首先,需要在项目的pom.xml文件中引入EasyExcel的依赖。可以使用以下代码将依赖添加到pom.xml文件中: ```xml <!-- 导出excel --> <dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>1.1.2-beta5</version> </dependency> ``` 接下来,在Controller中编写导出Excel的方法。可以使用以下代码作为参考: ```java /** * 学生信息导出 */ @RequestMapping(value = "api/url", method = RequestMethod.POST) public void studentExportExcel(HttpServletResponse response, @RequestBody StudentBean bean) { // 查询需要导出的数据 List<StudentExportBean> studentExportList = studentDao.studentExport(bean); // 设置表头 String\[\] headers = new String\[\]{"年级", "学号", "姓名", "专业", "二级学院", "联系方式", "性别"}; // 设置导出文件名 String fileName = "学生信息表"; // 调用Excel导出工具类进行导出 ExcelExport.export(response, studentExportList, headers, fileName, 6); } ``` 在上述代码中,首先从数据库中查询需要导出的学生信息数据,然后设置表头和导出文件名。最后,调用ExcelExport.export方法进行导出。请注意,ExcelExport是一个自定义的工具类,用于实现Excel导出的具体逻辑。 希望以上信息对您有所帮助。 #### 引用[.reference_title] - *1* [SpringBoot实现excel表格导出](https://blog.csdn.net/Hello_mengkebao/article/details/119597062)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [SpringBoot导出Excel工具类](https://blog.csdn.net/qq_41341640/article/details/109067688)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值