将对象列表转换为Excel(Java)

dgjrabp2  于 2023-02-11  发布在  Java
关注(0)|答案(1)|浏览(197)

是否有一种方法可以转换对象列表(例如)

List<Responsediff> differences;

其中Responsediff类类似于:

public class Responsediff{    
    
    private String balanceName;
    private String balance1;
    private String balance2;
    private String differenceinbalances;
}

直接转换为Excel文档?我目前正在使用openCSV将其转换为csv,但由于我的数据涉及精确的数字,我希望我是否可以将对象的lsit转换为Excel文件

mzmfm0qo

mzmfm0qo1#

下面是POI库的一个简单实现。此代码假设列表中的对象具有相同的结构,即它们具有相同的字段数量和类型。您可以通过使用Map或Map列表存储标题名称和数据类型来扩展它以处理不同的结构。

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;

import java.io.FileOutputStream;
import java.util.List;

public class ObjectToExcel {

public static void convertToExcel(List<Object> objects, String fileName) {
    // Creating a Workbook
    Workbook workbook = new XSSFWorkbook();

    // Creating a Sheet
    Sheet sheet = workbook.createSheet("Objects");

    // Creating a Font for styling header cells
    Font headerFont = workbook.createFont();
    headerFont.setBold(true);
    headerFont.setFontHeightInPoints((short) 14);
    headerFont.setColor(IndexedColors.RED.getIndex());

    // Creating a CellStyle for styling header cells
    CellStyle headerCellStyle = workbook.createCellStyle();
    headerCellStyle.setFont(headerFont);

    // Creating a Row
    Row headerRow = sheet.createRow(0);

    // Creating cells
    for (int i = 0; i < objects.size(); i++) {
        Object object = objects.get(i);
        // Get the object's class
        Class<?> objectClass = object.getClass();

        // If this is the first object, then create header cells
        if (i == 0) {
            // Get all fields in the class
            Field[] fields = objectClass.getDeclaredFields();

            // Create header cells
            for (int j = 0; j < fields.length; j++) {
                Cell cell = headerRow.createCell(j);
                cell.setCellValue(fields[j].getName());
                cell.setCellStyle(headerCellStyle);
            }
        }

        // Create a row
        Row row = sheet.createRow(i + 1);

        // Get all fields in the class
        Field[] fields = objectClass.getDeclaredFields();

        // Create cells for the object's values
        for (int j = 0; j < fields.length; j++) {
            try {
                Cell cell = row.createCell(j);
                fields[j].setAccessible(true);
                Object value = fields[j].get(object);
                if (value != null) {
                    if (value instanceof String) {
                        cell.setCellValue((String) value);
                    } else if (value instanceof Integer) {
                        cell.setCellValue((Integer) value);
                    } else if (value instanceof Double) {
                        cell.setCellValue((Double) value);
                    }
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

    // Resize all columns to fit the content size
    for (int i = 0; i < objects.size(); i++) {
        sheet.autoSizeColumn(i);
    }

    // Writing data to an excel file
    try {
        FileOutputStream fileOut = new FileOutputStream(fileName);
        workbook.write(fileOut);
        fileOut.close();
            workbook.close();
        System.out.println("Excel file created successfully at " + fileName);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

相关问题