首页 > 解决方案 > 用 XSSFRow 填充组合框

问题描述

我想用从 Excel 表中获取的行号填充组合框,问题是我无法循环行,因为 combobox.addItem() 只接受字符串。还有什么其他解决方案可以解决这个问题?我得到的错误:

XSSFRow cannot be converted to String

我的代码:

int lastRow = sheets.getLastRowNum();
for (int i=0;i<lastRow;i++){
    XSSFRow row = sheets.getRow(i);
    chooseRowComboBox.addItem(row);
}

标签: javaapache-poi

解决方案


你不能得到整行。我想你想得到填充行的行号。因此,您应该尝试以下方法:

public int getNonBlankRowCount(String path) throws IOException{
    File excel = new File(path);
    FileInputStream fis = new FileInputStream(excel);
    XSSFWorkbook book = new XSSFWorkbook(fis);
    XSSFSheet sheet = book.getSheetAt(1);
    int rowCount = 0;
    int index = book.getSheetIndex(sheet);
    if(index==-1){
        rowCount=-1;
        return rowCount;
    }
    else{
        sheet=book.getSheetAt(index);
        Iterator<Row> rowIterator = sheet.rowIterator();
        rowCount=0;
        while(rowIterator.hasNext()){
            Row row = (Row) rowIterator.next();
            XSSFCell cell =(XSSFCell) row.getCell(0, Row.RETURN_BLANK_AS_NULL);
            if(cell == null){
                break;
            }
            rowCount++;
        }
        return rowCount;
    }
}

此方法将计算您填充的行。现在您只需要将返回值打印到您的组合框中,例如:

for(int i=0; i<getNonBlankRowCount("path_to_ur_excel"); i++){
    chooseRowComboBox.addItem(Integer.toString(i)
}

如果你想获取所有行,你只需迭代 throw all rows 或设置 0 < i < 1048577 (最大行数)


推荐阅读