Search code examples
javaapache-poipoi-hssfhssf

Java. HSSF. Apache-poi. How to modificate code


My data is stored in a format(look down): [-] means a blank cell, on the right may be only 10 columns, after the space. Something like this:
[string0] [-] [string1] [string2] [string3] .. [string10] [-]

How to change this code for:

1) obtain only [string0]

2) obtain only [string1] [string2] [string3] .. [string10] [-]

    try {

    FileInputStream file = new FileInputStream("C:\\Users\\student3\\"+sfilename+".xls");

    //Get the workbook instance for XLS file
    HSSFWorkbook workbook = new HSSFWorkbook(file);

    //Get first sheet from the workbook
    HSSFSheet sheet = workbook.getSheetAt(0);

    //Iterate through each rows from first sheet
    Iterator<Row> rowIterator = sheet.iterator();
    while(rowIterator.hasNext()) {
        Row row = rowIterator.next();

        //For each row, iterate through each columns
        Iterator<Cell> cellIterator = row.cellIterator();
        while(cellIterator.hasNext()) {

            Cell cell = cellIterator.next();

            switch(cell.getCellType()) {
                case Cell.CELL_TYPE_STRING:
                    System.out.print(cell.getStringCellValue() + "\t\t");
                    list1.add(cell.getStringCellValue());
                    break;
            }
        }
        System.out.println("");
    }
    file.close();
    FileOutputStream out =
            new FileOutputStream("C:\\Users\\student3\\"+sfilename+".xls");
    workbook.write(out);
    out.close();

I don't know how to stop Iterator. He absorbs all..


Solution

  • If I am clear you just want to filter your first column string and rest seperately.

    Why not you just use a simple counter for this:

     while(rowIterator.hasNext()) {
        Row row = rowIterator.next();
        String RowContent = null;
        Iterator<Cell> cellIterator = row.cellIterator();
        while(cellIterator.hasNext()) {
            Cell cell = cellIterator.next();
            RowContent=RowContent+cell.toString();
        }
        //Code for saving RowContent or printing or whatever you want for text in complete row
    }
    

    RowContent will give concatenation of each cells of a single row in each iteration.