Home > Software engineering >  If cell in specific row contains "x", how to do I retrieve the specific column name where
If cell in specific row contains "x", how to do I retrieve the specific column name where

Time:10-29

Sample excel sheet (I am using a much larger excel sheet):

Column0 Column1 Column2 Column3 Column4 Column5
row0 red x x x
row1 orange x x
row2 yellow x x x
row3 green x x x
row4 blue x x
row5 purple x x
row6 pink x

Let's propose I want to select row3. How do I retrieve the name of the columns where the x' are present? For row3, I want to display on my console "column2 column3 column5". I am also trying to start at a specific column index hence I had a column that strayed from having x's. So for the example, I need to iterate from column2-->column5, then identify in row3 which of the cells have x's and then identify the name of those columns. My code below I had real time numbers I am using.

//find x's in certain row
        //pick row 15
        int rowIndex = 15;
        //start at column 9 and iterate to column 33
        for (int columnIndex = 9; columnIndex<33; columnIndex  ){
            Row row = CellUtil.getRow(rowIndex, sheet);
            Cell cell = CellUtil.getCell(row, columnIndex);
            //if row contains x in specific cells, get column name
            //progTypes is the name of the columns appearing in row index 0
            if(cell.getStringCellValue() == "x") {
                for(int progTypes = 9; progTypes < 33; progTypes  ) {
                    for (int firstRow = 0; firstRow < 0; firstRow  ) {
                        Row fRow = CellUtil.getRow(firstRow, sheet);
                        Cell fColumn = CellUtil.getCell(fRow, progTypes);
                        String columnName = fColumn.getStringCellValue();
                        System.out.println(columnName);
                    }
                }
            }

CodePudding user response:

Make use of Apache POI. There are a number of examples how to access and modify spreadsheets at https://poi.apache.org/components/spreadsheet/examples.html

CodePudding user response:

If I understood correctly you don't need the two for loops inside your if case since you already got the cell index.

if(cell.getStringCellValue() == "x") {
  Row fRow = CellUtil.getRow(0, sheet);
  Cell fColumn = CellUtil.getCell(fRow, columnIndex);
  String columnName = fColumn.getStringCellValue();
  System.out.println(columnName);
}
  • Related