poi针对List<T>通用导出excel功能

今天遇上导出excel的功能,网上搜了一下,
参考了这篇文章:Java之——导出Excel通用工具类_冰河的专栏-CSDN博客_java导出excel工具类
对代码做了进一步做了优化处理:
支持List<Map>。
指定需要导出的属性。
抽取出了重复的方法。
对每个元素都要获取反射信息做了缓存优化。
修正输出内容时的bug。
poi升级为4.1.2版本。
pom:

<dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-scratchpad</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-excelant</artifactId>
            <version>4.1.2</version>
        </dependency>

具体代码:
 

import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

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.CellBase;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
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;
 
 
/**
 * 导出Excel
 *
 * @param <T>
 */
public class ExportExcelUtil<T>{
    
    // 2007 版本以上 最大支持1048576行
    public  final static String  EXCEl_FILE_2007 = "2007";
    // 2003 版本 最大支持65536 行
    public  final static String  EXCEL_FILE_2003 = "2003";
    
    //private Pattern patternData = Pattern.compile("^//d+(//.//d+)?$");
    
    /**
     * <p>
     * 导出无头部标题行Excel <br>
     * 时间格式默认:yyyy-MM-dd hh:mm:ss <br>
     * </p>
     * 
     * @param title 表格标题
     * @param dataset 数据集合
     * @param out 输出流
     * @param version 2003 或者 2007,不传时默认生成2003版本
     */
    public void exportExcel(String title, Collection<T> dataset, OutputStream out, String version) {
        if(StringUtils.isEmpty(version) || EXCEL_FILE_2003.equals(version.trim())){
            exportExcel2003(title, null,null, dataset, out, "yyyy-MM-dd HH:mm:ss");
        }else{
            exportExcel2007(title, null,null, dataset, out, "yyyy-MM-dd HH:mm:ss");
        }
    }
 
    /**
     * <p>
     * 导出带有头部标题行的Excel <br>
     * 时间格式默认:yyyy-MM-dd hh:mm:ss <br>
     * </p>
     * 
     * @param title 表格标题
     * @param headers 头部标题集合
     * @param fieldsName 需要导出的字段名,不区分大小写
     * @param dataset 数据集合
     * @param out 输出流
     * @param version 2003 或者 2007,不传时默认生成2003版本
     */
    public void exportExcel(String title,String[] headers, String[] fieldsName,Collection<T> dataset, OutputStream out,String version) {
        if(StringUtils.isBlank(version) || EXCEL_FILE_2003.equals(version.trim())){
            exportExcel2003(title, headers,fieldsName, dataset, out, "yyyy-MM-dd HH:mm:ss");
        }else{
            exportExcel2007(title, headers,fieldsName, dataset, out, "yyyy-MM-dd HH:mm:ss");
        }
    }
 
    /**
     * <p>
     * 通用Excel导出方法,利用反射机制遍历对象的所有字段,将数据写入Excel文件中 <br>
     * 此版本生成2007以上版本的文件 (文件后缀:xlsx)
     * </p>
     * 
     * @param sheetName
     *            表格标题名
     * @param headers
     *            表格头部标题集合
     * @param dataset
     *            需要显示的数据集合,集合中一定要放置符合JavaBean风格的类的对象。此方法支持的
     *            JavaBean属性的数据类型有基本数据类型及String,Date
     * @param out
     *            与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中
     * @param dateDtf
     *            如果有时间数据,设定输出格式。默认为"yyyy-MM-dd hh:mm:ss"
     */
    public void exportExcel2007(String sheetName, String[] headers,String[] fieldsName, Collection<T> dataset, OutputStream out, String dateDtf) {
        // 声明一个工作薄
        XSSFWorkbook workbook = new XSSFWorkbook();
        // 生成一个表格
        XSSFSheet sheet = workbook.createSheet(sheetName);
        // 设置表格默认列宽度为15个字节
        sheet.setDefaultColumnWidth(20);
        // 生成一个样式
        XSSFCellStyle style = workbook.createCellStyle();
        // 生成一个字体
        XSSFFont font = workbook.createFont();
        font.setFontName("宋体"); 
        font.setFontHeightInPoints((short) 11);
        // 把字体应用到当前的样式
        style.setFont(font);
        // 生成并设置另一个样式
        XSSFCellStyle style2 = workbook.createCellStyle();
        // 生成另一个字体
        XSSFFont font2 = workbook.createFont();
        // 把字体应用到当前的样式
        style2.setFont(font2);
 
        // 产生表格标题行
        XSSFRow row = sheet.createRow(0);
        XSSFCell cellHeader;
        for (int i = 0; i < headers.length; i++) {
            cellHeader = row.createCell(i);
            cellHeader.setCellStyle(style);
            cellHeader.setCellValue(new XSSFRichTextString(headers[i]));
        }
 
        // 遍历集合数据,产生数据行
        Iterator<T> it = dataset.iterator();
        int index = 0;
        T item;
        Map<String,Method> getMethodMap = new HashMap<>();
        XSSFCell cell;
        Object value;
        SimpleDateFormat sdf = new SimpleDateFormat(dateDtf);
        while (it.hasNext()) {
            index++;
            row = sheet.createRow(index);
            item = (T) it.next();
            for (int i = 0; i < fieldsName.length; i++) {
                String currFieldName = fieldsName[i];
                cell = row.createCell(i);
                cell.setCellStyle(style2);
                
                try {
                    value = getItemValue(item, getMethodMap, currFieldName);
                    // 判断值的类型后进行强制类型转换
                    handleCellValue(cell, value, sdf);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    
                }
            }
        }
        writeExcel(out, workbook);
    }
    
    
    
    /**
     * <p>
     * 通用Excel导出方法,利用反射机制遍历对象的所有字段,将数据写入Excel文件中 <br>
     * 此方法生成2003版本的excel,文件名后缀:xls <br>
     * </p>
     * 
     * @param sheetName
     *            表格标题名
     * @param headers
     *            表格头部标题集合
     * @param fieldsName
     *            需要导出的字段名数组,不区分大小写
     * @param dataset
     *            需要显示的数据集合,集合中一定要放置符合JavaBean风格的类的对象。此方法支持的
     *            JavaBean属性的数据类型有基本数据类型及String,Date
     * @param out
     *            与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中
     * @param pattern
     *            如果有时间数据,设定输出格式。默认为"yyyy-MM-dd hh:mm:ss"
     */
    public void exportExcel2003(String sheetName, String[] headers,String[] fieldsName, Collection<T> dataset, OutputStream out, String pattern) {
        // 声明一个工作薄
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 生成一个表格
        HSSFSheet sheet = workbook.createSheet(sheetName);
        // 设置表格默认列宽度为15个字节
        sheet.setDefaultColumnWidth(20);
        // 生成一个样式
        HSSFCellStyle style = workbook.createCellStyle();
        // 生成一个字体
        HSSFFont font = workbook.createFont();
        font.setFontName("宋体"); 
        font.setFontHeightInPoints((short) 11);
        // 把字体应用到当前的样式
        style.setFont(font);
        // 生成并设置另一个样式
        HSSFCellStyle style2 = workbook.createCellStyle();
        // 生成另一个字体
        HSSFFont font2 = workbook.createFont();
        // 把字体应用到当前的样式
        style2.setFont(font2);
 
        // 产生表格标题行
        HSSFRow row = sheet.createRow(0);
        HSSFCell cellHeader;
        for (int i = 0; i < headers.length; i++) {
            cellHeader = row.createCell(i);
            cellHeader.setCellStyle(style);
            cellHeader.setCellValue(new HSSFRichTextString(headers[i]));
        }
 
        Iterator<T> it = dataset.iterator();
        int index = 0;
        T item=null;
        Map<String,Method> getMethodMap = new HashMap<>();
        HSSFCell cell;
        Object value;
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        while (it.hasNext()) {
            index++;
            row = sheet.createRow(index);
            item = (T) it.next();
            for (int i = 0; i < fieldsName.length; i++) {
                String currFieldName = fieldsName[i];
                cell = row.createCell(i);
                cell.setCellStyle(style2);
                
                try {
                    value = getItemValue(item, getMethodMap, currFieldName);
                    handleCellValue(cell, value, sdf);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    // 清理资源
                }
            }
        }
        writeExcel(out, workbook);
    }

    private void handleCellValue(CellBase cell, Object value, SimpleDateFormat sdf) {
        if (value==null || value instanceof String) {
            cell.setCellValue(value!=null?value.toString():"");
        }else if (value instanceof Integer) {
            cell.setCellValue((Integer) value);
        } else if (value instanceof Float) {
            cell.setCellValue((Float) value);
        } else if (value instanceof Double) {
            cell.setCellValue((Double) value);
        } else if (value instanceof Long) {
            cell.setCellValue((Long) value);
        }else if(value instanceof Boolean) {
            cell.setCellValue((Boolean) value ? "是" : "否");
        } else if (value instanceof Date) {
            cell.setCellValue(sdf.format((Date) value));
        } else {
            cell.setCellValue(value.toString());
        }
    }

    private void writeExcel(OutputStream out, Workbook workbook) {
        try {
            workbook.write(out);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                workbook.close();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private Object getItemValue(T item, Map<String, Method> getMethodMap, String currFieldName)
            throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        if(item instanceof Map){
            return ((Map<?, ?>)item).get(currFieldName);
        }
        Field field = null;
        String fieldName = null;
        String getMethodName = null;
        Class<?> tClass = null;
        Method getMethod = null;
        Object value = null;
        if(!getMethodMap.containsKey(currFieldName)){
            Field[] fields = item.getClass().getDeclaredFields();
            for (int f = 0; f < fields.length; f++) {
                field = fields[f];
                fieldName = field.getName();
                if(fieldName.equalsIgnoreCase(currFieldName)){
                    getMethodName = "get" + fieldName.substring(0, 1).toUpperCase()
                            + fieldName.substring(1);
                    tClass = item.getClass();
                    getMethod = tClass.getMethod(getMethodName, new Class[] {});
                    getMethodMap.put(currFieldName, getMethod);
                    break;
                }
            }
        }

        getMethod = getMethodMap.get(currFieldName);
        if(getMethod!=null){//执行反射方法
            value = getMethod.invoke(item, new Object[] {});
        }
        return value==null?"":value;
    }
}
 
import java.net.URLEncoder;
import java.util.Collection;
 
import javax.servlet.http.HttpServletResponse;
 
import org.apache.commons.lang3.StringUtils;
 
/**
 * 包装类
 *
 * @param <T>
 */
public class ExportExcelWrapper<T> extends ExportExcelUtil<T> {
    /**
     * <p>
     * 导出带有头部标题行的Excel <br>
     * 时间格式默认:yyyy-MM-dd hh:mm:ss <br>
     * </p>
     * 
     * @param title 表格标题
     * @param headers 头部标题集合
     * @param dataset 数据集合
     * @param out 输出流
     * @param version 2003 或者 2007,不传时默认生成2003版本
     */
    public void exportExcel(String fileName, String title, String[] headers,String[] fieldsName, Collection<T> dataset, HttpServletResponse response,String version) {
        try {
            boolean is2003 = StringUtils.isBlank(version) || EXCEL_FILE_2003.equals(version.trim());
            response.setContentType("application/vnd.ms-excel");  
            response.addHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName, "UTF-8") + (is2003?".xls":".xlsx"));
            if(is2003){
                exportExcel2003(title, headers,fieldsName, dataset, response.getOutputStream(), "yyyy-MM-dd HH:mm:ss");
            }else{
                exportExcel2007(title, headers,fieldsName, dataset, response.getOutputStream(), "yyyy-MM-dd HH:mm:ss");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

springboot里的使用:
 

@ApiOperation(value = "导出车辆统计数据", notes = "导出车辆统计数据")
@GetMapping(value = "/expStatVehicleByRange")
 public void expStatVehicleByRange(QueryStatParam params,HttpServletResponse response) {
List<StatVehicleDTO> statList =xxxxxxxxxxxxxxxxxxxxxxxx
String[] columnNames = { "小区名称", "车辆数", "异常数"};//指定excel标题列名
String[] fieldsName={"communityName","regVehicleCnt","abnormalyCnt"};//及对象的属性数组,不区分大小写。
ExportExcelWrapper<StatVehicleDTO> util = new ExportExcelWrapper<>();
util.exportExcel("小区车辆统计数据", "车辆数据", columnNames, fieldsName,statList, response, ExportExcelUtil.EXCEl_FILE_2007);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值