【问题标题】:Writing from ArrayList to Excel sheet ListIterator从 ArrayList 写入 Excel 工作表 ListIterator
【发布时间】:2026-02-11 10:25:01
【问题描述】:

我有一个 ArrayList,其中包含有关员工的信息,例如 fName、sName 和地址。我正在使用 apache poi 将其写入 Excel 工作簿。

在 Excel 表中,我希望有关一名员工的所有信息都出现在同一行中。我设法在第 1 行和第 0 单元格中写下名字(第 0 行包含标题)。一切都井井有条。当尝试添加姓氏时,一切都开始在这里和那里跳跃。

如何将 sName 写在正确的位置?

这是我的excel代码的一部分

private void writeEmployeeInfo() {

    ListIterator<Employee> employeeListIterator = Employee
            .getEmployeeList().listIterator();

    int rowIndex = 1;
    int cellIndex = 0;


    while (employeeListIterator.hasNext()) {

        Employee employee = employeeListIterator.next();

        Row row = sheet.createRow(rowIndex++);

        Cell cell = row.createCell(cellIndex);

        cell.setCellValue(employee.getfName());

// 尝试在右侧单元格中添加员工的姓氏。

            while(employeeListIterator.hasNext()){
            Employee emp = employeeListIterator.next();
            row = sheet.createRow(rowIndex++);
            cell = row.createCell(cellIndex++);
            cell.setCellValue(emp.getsName());
        }
    }
}

这是我在这里的第一篇文章,所以如果我写的或做的事情很糟糕,请告诉我该怎么做,这样你们就很容易理解我的问题。

如果您需要查看更多代码,这里是项目的链接:http://1drv.ms/1kSGfDm

【问题讨论】:

    标签: java excel arraylist listiterator


    【解决方案1】:

    您没有发布如何添加其他单元格。试试这样的:

    private void writeEmployeeInfo() {
    
        ListIterator<Employee> employeeListIterator = Employee
                .getEmployeeList().listIterator();
    
        int rowIndex = 1;
    
        while (employeeListIterator.hasNext()) {
    
            Employee employee = employeeListIterator.next();
    
            Row row = sheet.createRow(rowIndex++);
    
            row.createCell(0).setCellValue(employee.getfName());
            row.createCell(1).setCellValue(employee.getSName());
            row.createCell(2).setCellValue(employee.getAddress);
        }
    }
    

    【讨论】:

    • 我试图避免做你所说的。我正在使用两个计数器;行索引和单元格索引。在单元格 0、第 1、2、3 行等中添加雇员列表中所有对象的名字后。我想移动到单元格 1 行、1、2、3 等并添加确定名称。我想在不编写创建单元格/行的情况下执行此操作,但使用计数器(rodIndex 和 cellIndex)。
    • 您能粘贴您尝试过但没有按预期工作的代码吗?否则我很难理解你为什么需要两个计数器。
    • 现在有意义吗?我更新了我的问题。我需要一个行计数器(垂直)和一个单元格计数器(水平)。我首先将employeeList中所有对象的名字写入excel工作簿。然后我想水平移动一个单元格并写下列表中所有对象的姓氏。也许我的整个方法都错了?
    • 这不能简单地使用两个计数器来完成,因为列的数量取决于员工属性(fName、SName、Address),这些属性不是可枚举的值。更重要的是,在第一次迭代时,您正在创建行,而在每次其他迭代时,您都需要重用以前创建的行。
    • 可以先只将 fNames 写入第一列,然后再写入另一列,但您的代码会比上面发布的更复杂。