用XSSFRow填充组合框

时间:2018-07-20 19:54:30

标签: java apache-poi

我想用从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);
}

2 个答案:

答案 0 :(得分:0)

You can't get the whole row.. I think you want to get the rownumbers of the filled rows. So you should try something like:

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;
    }
}

This method will count ur filled rows. Now u just need to print the returned value into ur combobox like:

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

If u want to get all rows, you just iterate threw all rows or set 0 < i < 1048577 (the max number of excel rows)

答案 1 :(得分:0)

此代码与我配合良好:

int lastRow = sheets.getLastRowNum() + 1;    
for (int i=1; i<=lastRow; i++){
        XSSFRow currentRow = sheets.getRow(i); 
        if (currentRow != null && currentRow.getCell(0) != null) {
                    chooseRowComboBox.addItem(String.valueOf(i));
                }
            }