Java生成excel表格

本文介绍了一个使用Java实现的Excel文件生成器,该生成器能够从指定的实体类列表中读取数据并将其写入到Excel文件中。文章详细展示了如何通过反射机制获取实体类的所有字段,并将这些字段作为表头;同时,还介绍了如何调用实体类的方法来获取字段值并写入单元格。

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

导入实体的类的list和文件输出流生成XX.slx文件

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.Date;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class ExcelBuilder<T> {

    @SuppressWarnings("unchecked")
    public void buildExcel(List<T> list, OutputStream out) {

        //如果列表为空就不生成表
        if (list.isEmpty()) {return;}

        Object entity = null;
        Class<T> entityClass = null;
        Field[] fields = null;
        HSSFWorkbook workbook = null;
        HSSFSheet sheet = null;
        HSSFCellStyle style = null;
        HSSFRow row = null;
        HSSFCell cell = null;

        int rowIndex = 0; //行计数
        for (int count = 0; count <= list.size(); count++) { //循环比list的size多一次
            if (rowIndex == 0) { //第一次获取泛型的类信息
                entity = list.get(rowIndex);
                System.out.println("第一个实体类:" + entity);
                entityClass = (Class<T>) entity.getClass();
                System.out.println("clazz = " + entityClass.getName()); //获取类名

                fields = entityClass.getDeclaredFields();
                System.out.println("fieldsNumber = " + fields.length); //获取属性个数

                for (Field field : fields) {
                    System.out.println("fieldName = " + field.getName()); //获取每个属性名
                }

                workbook = new HSSFWorkbook(); ////创建excel文件和表
                sheet = workbook.createSheet(); 

                style = workbook.createCellStyle();  // 创建一个居中格式
                style.setAlignment(HSSFCellStyle.ALIGN_CENTER);

                row = sheet.createRow(rowIndex); ////设置表头字段(首行)
                for (short i = 0; i < fields.length; i++) {
                    cell = row.createCell(i);
                    cell.setCellStyle(style);
                    cell.setCellValue(fields[i].getName());
                }
                rowIndex++;
            }
            else {
                row = sheet.createRow(rowIndex);
                for (short i = 0; i < fields.length; i++) {

                    String name = null;
                    String methodName = null;
                    Method method = null;                   
                    Object fieldValue = null;

                    try {
                        name = fields[i].getName().substring(0, 1).toUpperCase() + fields[i].getName().substring(1);
                        methodName = "get" + name;
                        method = entityClass.getMethod(methodName);
                        entity = list.get(count-1); //获取实体类
                        fieldValue = method.invoke(entity);
                    } catch (NoSuchMethodException e) {
                        e.printStackTrace();
                    } catch (SecurityException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (IllegalArgumentException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    }

                    cell = row.createCell(i);
                    cell.setCellStyle(style);

                    if (fieldValue instanceof Integer) {  
                        Integer intValue = (Integer) fieldValue;  
                        cell.setCellValue(intValue);
                    } else if (fieldValue instanceof Float) {  
                        float fValue = (Float) fieldValue;  
                        cell.setCellValue(fValue);
                    } else if (fieldValue instanceof Double) {  
                        double dValue = (Double) fieldValue;  
                        cell.setCellValue(dValue);  
                    } else if (fieldValue instanceof Long) {
                        long lValue = (Long) fieldValue;
                        cell.setCellValue(lValue);  
                    } else if (fieldValue instanceof Boolean) {  
                        boolean bValue = (Boolean) fieldValue;
                        cell.setCellValue(bValue?"男":"女"); //男生true
                    }  else if (fieldValue instanceof Date)  
                    {  
                        Date date = (Date) fieldValue;  
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
                        cell.setCellValue(sdf.format(date));  
                    } else {
                        cell.setCellValue(fieldValue.toString());
                    } 
                }
                rowIndex++;
            }
        }
        try {
            workbook.write(out);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }  
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值