繁体   English   中英

在Java中使用Apache Poi的Excel工作表合并单元格读取

[英]Excel sheet merged cell reading using apache poi in java

我正在使用Java中的Apache poi阅读excel表,并且正在使用CellRangeAddress来获取区域。

情况1:如果我要提供2-3个数据以进行合并并进入下一个单元格,则可以。 我正在下一个合并区域。

情况2:如果我给出了6个以上的值并转到下一个区域,则显示合并区域的IndexOutofBoundException

这里的代码:

List<OrganizationDB> orgList = new ArrayList<OrganizationDB>();
List<EmployeeDB> empList;
XSSFWorkbook workBook;
XSSFSheet excelSheet;
XSSFRow row;
XSSFCell cells;
TreeViewer treeViewer = null;


File excelFile = new File("D:\\ExcelExport\\ExcelSheet2.xls");
FileInputStream fis;

if (excelFile.exists()) {
    fis = new FileInputStream(excelFile);

    workBook = new XSSFWorkbook(fis);
    excelSheet = workBook.getSheetAt(0);

    int count  = 1;     

    while (count <= excelSheet.getLastRowNum()) {               

        CellRangeAddress region = excelSheet.getMergedRegion(count);
        row = excelSheet.getRow(count);
        //XSSFCell cell = row.getCell(0);

        orgDb = new OrganizationDB();

        orgDb.setOrganizationName(row.getCell(0).getStringCellValue());
        orgDb.setCityName(row.getCell(4).getStringCellValue());
        orgDb.setStateName(row.getCell(5).getStringCellValue());

        empList = new ArrayList<EmployeeDB>();

        while(count<=region.getLastRow()) {

            row = excelSheet.getRow(count);
            empDb = new EmployeeDB();

            empDb.setCompanyName(row.getCell(0).getStringCellValue());
            empDb.setEmpID(row.getCell(1).getStringCellValue());
            empDb.setEmpName(row.getCell(2).getStringCellValue());
            empDb.setPhoneNo((int) row.getCell(3).getNumericCellValue());
            empList.add(empDb);
            orgDb.setEmpList(empList);
            count++;
        }
        orgList.add(orgDb);
    }

我在您的代码中看到了一个逻辑,但我不完全理解。 你能检查一下吗? 你有一个计数器count嵌套while循环由两个使用。

while (count <= excelSheet.getLastRowNum()) {
            CellRangeAddress region      = excelSheet.getMergedRegion(count);
...
    while(count<=region.getLastRow()){
...
        count++;

也许有两个合并的区域,行1到3和4到6,然后在第一次运行您的top while count = 3,因为嵌套while增加了它。 然后代码尝试获取mergedRegion(3),并且没有索引为3的mergedRegion。它必须与具有下一组行的mergedRegion(2)代替...

我猜您必须为mergedRegions和其中的行使用不同的计数器。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM