java导出excel表格的Util类(含父类属性)

本文介绍了一款基于Java的实用工具类,用于导出数据到Excel表格,支持2007版本以上的Excel文件格式。该工具类通过反射机制获取JavaBean的属性,并将数据动态写入Excel,同时提供了对各种数据类型的处理,包括日期、数字和文本。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.pangding.web.order.util;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.xssf.usermodel.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.lang.reflect.Field;

/**
 * @author Shallow
 * @date 2019/7/1 15:35
 * @description 导出Excel表格
 */
public class ExcelUtil<T> {

        private final static Pattern PATTERN = Pattern.compile("^//d+(//.//d+)?$");

        public void exportExcel(String fileName, String title, String[] headers, Collection<T> dataset, HttpServletResponse response) {
            try {
                response.setContentType("application/vnd.ms-excel");
                response.addHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName, "UTF-8") + ".xls");
                exportExcel2007(title, headers, dataset, response.getOutputStream());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @SuppressWarnings({ "unchecked", "rawtypes" })
        private void exportExcel2007(String title, String[] headers, Collection<T> dataset, OutputStream out) {
            // 声明一个工作薄
            XSSFWorkbook workbook = new XSSFWorkbook();
            // 生成一个表格
            XSSFSheet sheet = workbook.createSheet(title);
            // 设置表格默认列宽度为15个字节
            sheet.setDefaultColumnWidth(20);
            // 生成一个样式
            XSSFCellStyle style = workbook.createCellStyle();
            // 设置这些样式
            style.setFillForegroundColor(new XSSFColor(java.awt.Color.gray));
            style.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
            style.setBorderBottom(XSSFCellStyle.BORDER_THIN);
            style.setBorderLeft(XSSFCellStyle.BORDER_THIN);
            style.setBorderRight(XSSFCellStyle.BORDER_THIN);
            style.setBorderTop(XSSFCellStyle.BORDER_THIN);
            style.setAlignment(XSSFCellStyle.ALIGN_CENTER);
            // 生成一个字体
            XSSFFont font = workbook.createFont();
            font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
            font.setFontName("宋体");
            font.setColor(new XSSFColor(java.awt.Color.BLACK));
            font.setFontHeightInPoints((short) 11);
            // 把字体应用到当前的样式
            style.setFont(font);

            // 产生表格标题行
            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]));
            }

            style.setFillForegroundColor(new XSSFColor(java.awt.Color.WHITE));
            style.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
            // 生成另一个字体
            XSSFFont font2 = workbook.createFont();
            font2.setBoldweight(XSSFFont.BOLDWEIGHT_NORMAL);
            // 把字体应用到当前的样式
            style.setFont(font2);

            // 遍历集合数据,产生数据行
            Iterator<T> it = dataset.iterator();
            int index = 0;
            T t;
            Field[] fields1;
            Field[] fields;
            Field field;
            XSSFRichTextString richString;
            Matcher matcher;
            String fieldName;
            String getMethodName;
            XSSFCell cell;
            Class tCls;
            Method getMethod;
            Object value;
            String textValue;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            while (it.hasNext()) {
                index++;
                row = sheet.createRow(index);
                t = it.next();
                // 利用反射,根据JavaBean属性的先后顺序,动态调用getXxx()方法得到属性值
                fields1 = t.getClass().getDeclaredFields();
                if(t.getClass().getSuperclass() != null){
                    Field[] superFields = t.getClass().getSuperclass().getDeclaredFields();
                    List list = new ArrayList(Arrays.asList(fields1));
                    list.addAll(Arrays.asList(superFields));
                    Field[] fields2 = new Field[list.size()];
                    list.toArray(fields2);
                    fields = fields2;
                }else {
                    fields=fields1;
                }
                int j = 0;
                for (int i = 0; i < fields.length; i++) {
                    field = fields[i];
                    fieldName = field.getName();
                    getMethodName = "get" + fieldName.substring(0, 1).toUpperCase()
                            + fieldName.substring(1);
                    try {
                        tCls = t.getClass();
                        getMethod = tCls.getMethod(getMethodName);
                        value = getMethod.invoke(t);
                        if(value == null){
                            continue;
                        }
                        // 判断值的类型后进行强制类型转换
                        textValue = null;
                        cell = row.createCell(j);
                        j++;
                        cell.setCellStyle(style);
                        if (value instanceof Integer) {
                            cell.setCellValue((Integer) value);
                        } else if (value instanceof Float) {
                            textValue = String.valueOf(value);
                            cell.setCellValue(textValue);
                        } else if (value instanceof Double) {
                            textValue = String.valueOf(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 = PATTERN.matcher(textValue);
                            if (matcher.matches()) {
                                // 是数字当作double处理
                                cell.setCellValue(Double.parseDouble(textValue));
                            } else {
                                richString = new XSSFRichTextString(textValue);
                                cell.setCellValue(richString);
                            }
                        }
                    } catch (SecurityException | NoSuchMethodException | IllegalArgumentException | IllegalAccessException | InvocationTargetException e) {
                        e.printStackTrace();
                    }
                }
            }
            try {
                workbook.write(out);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值