Java遍历Employees对象数组写入Excel报ClassCastException异常
问题描述
需要实现功能:定义Employees类,包含firstName、lastName、city三个属性,实例化多个该类对象存入数组后,遍历数组提取每个对象的三个属性值,写入Excel文件。
代码运行到第二个for循环块时触发中断,抛出异常:
Exception in thread "main" java.lang.ClassCastException: class http.Employees cannot be cast to class [Ljava.lang.Object; (http.Employees is in unnamed module of loader 'app'; [Ljava.lang.Object; is in module java.base of loader 'bootstrap') at http.App.main(App.java:64).
原始代码如下:
class Employees { String firstName; String lastName; String city; public Employees(String firstName, String lastName, String city) { this.firstName = firstName; this.lastName = lastName; this.city = city; } } public class App { public static void main(String[] args) throws Exception { String excelPath = "C:/Work/01_TSM/java/test.xlsx"; FileInputStream inputStream = new FileInputStream(new File(excelPath)); // create workbook object XSSFWorkbook workbook = new XSSFWorkbook(inputStream); // create spreadsheet object XSSFSheet spreadsheet = workbook.getSheetAt(1); // create row object XSSFRow row; // This data needs to be written in (Object[]) HashMap<Integer, Object> employeeData = new HashMap<Integer, Object>(); Employees employee1 = new Employees("John", "Smith", "CT"); Employees employee2 = new Employees("Jane", "Doe", "O"); Employees[] employees = { employee1, employee2 }; // Insert data for (int i = 0; i < employees.length; i++) { employeeData.put(i, employees[i]); } ; Set<Integer> keyid = employeeData.keySet(); int rowid = 1; // writing the data into the sheets for (Integer key : keyid) { row = spreadsheet.createRow(rowid++); // here the code breaks Object[] objectArr = (Object[]) employeeData.get(key); int cellid = 0; for (Object obj : objectArr) { Cell cell = row.createCell(cellid++); cell.setCellValue((String) obj); } } // writing the workbook into the file FileOutputStream out = new FileOutputStream(new File("C:/Work/01_TSM/java/test.xlsx")); workbook.write(out); out.close(); } }
错误原因
- 核心问题是类型不匹配:你往
employeeData中存入的value是单个Employees类实例,不是Object[]数组类型,执行强制转换(Object[]) employeeData.get(key)时必然抛出类型转换异常。Java不会自动把自定义类的实例拆成由属性组成的数组,必须手动提取属性值。 - 逻辑冗余:这里完全不需要使用HashMap中转数据,你已经定义好了
Employees类型的数组,直接遍历数组就能拿到所有员工数据,额外加一层Map只会增加出错概率。 - 资源泄漏风险:原始代码中
FileInputStream没有关闭,操作完Excel后可能残留文件锁。
修正后可运行代码
import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; class Employees { String firstName; String lastName; String city; public Employees(String firstName, String lastName, String city) { this.firstName = firstName; this.lastName = lastName; this.city = city; } } public class App { public static void main(String[] args) throws Exception { String excelPath = "C:/Work/01_TSM/java/test.xlsx"; // 用try-with-resources自动关闭流资源,避免泄漏 try (FileInputStream inputStream = new FileInputStream(new File(excelPath)); XSSFWorkbook workbook = new XSSFWorkbook(inputStream)) { XSSFSheet spreadsheet = workbook.getSheetAt(1); int rowid = 1; // 初始化员工数据 Employees[] employees = { new Employees("John", "Smith", "CT"), new Employees("Jane", "Doe", "O") }; // 直接遍历员工数组写入行 for (Employees emp : employees) { XSSFRow row = spreadsheet.createRow(rowid++); int cellid = 0; // 逐个写入三个属性到对应单元格 row.createCell(cellid++).setCellValue(emp.firstName); row.createCell(cellid++).setCellValue(emp.lastName); row.createCell(cellid++).setCellValue(emp.city); } // 写入文件并自动关闭输出流 try (FileOutputStream out = new FileOutputStream(new File(excelPath))) { workbook.write(out); } } } }
补充说明
如果你一定要保留HashMap的写法,需要在往Map存数据时,就把每个员工的属性封装成Object数组,后续强转才不会报错,示例如下:
HashMap<Integer, Object[]> employeeData = new HashMap<>(); for (int i = 0; i < employees.length; i++) { Employees emp = employees[i]; // 存的时候就组装成对象数组 employeeData.put(i, new Object[]{emp.firstName, emp.lastName, emp.city}); }
这种写法没有实际价值,仅作原理演示,不推荐使用。
内容的提问来源于stack exchange,提问作者marincean adrian
相关产品推荐
相关产品推荐

