Java生成excel表格

导入实体的类的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();
        }  
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是一个简单的Java代码示例,用于将数据导出为Excel表格: ``` import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelExporter { public void exportDataToExcel(List<String[]> data, String fileName) throws IOException { Workbook workbook = new XSSFWorkbook(); Sheet sheet = workbook.createSheet("Sheet1"); int rowNum = 0; for (String[] rowData : data) { Row row = sheet.createRow(rowNum++); int colNum = 0; for (String cellData : rowData) { Cell cell = row.createCell(colNum++); cell.setCellValue(cellData); } } FileOutputStream outputStream = new FileOutputStream(fileName); workbook.write(outputStream); workbook.close(); outputStream.close(); } public static void main(String[] args) throws IOException { List<String[]> data = new ArrayList<String[]>(); data.add(new String[] {"Name", "Age", "Gender"}); data.add(new String[] {"John", "25", "Male"}); data.add(new String[] {"Jane", "30", "Female"}); ExcelExporter exporter = new ExcelExporter(); exporter.exportDataToExcel(data, "example.xlsx"); } } ``` 这个例子使用Apache POI库来创建Excel工作簿和工作表,然后循环遍历数据列表并将其写入单元格。最后,将工作簿写入文件并关闭它。在主方法,创建一个包含示例数据的数据列表,然后将其传递给导出器对象,并指定要导出的文件名。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值