3

I am able to read the values in a first sheet, but not in the second one.

Well I am not an experienced in Java, and this is a very strange problem that I've been having.

I am trying to get values of columns corresponding to rows in an Excel file.

I am able to get the values in the first sheet properly.

However, in the second sheet, when I try to read all rows, it gives me a rowcount value of 1, although there are two rows of data.

In my method, I am passing the key and the column values to get the corresponding data. It works for the first sheet i.e. account, but does not work for the second sheet's employee.

Below is the method that I am using to read the Excel file using a ConfigurationFile Reader, and then put those values in a Map, and then call the method to read the cell values:

package TestFramework;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Map;

public class TestExcel {


    public static Map<String, Map<String,String>> map = new HashMap<String, Map<String, String>>();

    public static void readExcel(String fileName, String sheetName) throws IOException {
        ConfigFileReader config = new ConfigFileReader();
        String excelFilePath = config.getDataModelPath();
        //Create an object of File class to open xlsx file
        File file = new File(excelFilePath);
        //Create an object of FileInputStream class to read excel file
        FileInputStream inputStream = new FileInputStream(file);
        Workbook myWorkbook = null;
        //Find the file extension by splitting file name in substring  and getting only extension name
        String fileExtensionName = fileName.substring(fileName.indexOf("."));
        //Check condition if the file is xlsx file
        if (fileExtensionName.equals(".xlsx")) {
            //If it is xlsx file then create object of XSSFWorkbook class
            myWorkbook = new XSSFWorkbook(inputStream);
        }
        //Check condition if the file is xls file
        else if (fileExtensionName.equals(".xls")) {
            //If it is xls file then create object of HSSFWorkbook class
            myWorkbook = new HSSFWorkbook(inputStream);
        }

        //Read sheet inside the workbook by its name
        Sheet excelSheet = myWorkbook.getSheet(sheetName);
        //Find number of rows in excel file
        int rowCount = excelSheet.getLastRowNum() - excelSheet.getFirstRowNum();

        Row header = null;

        for (int rowIndex = 0; rowIndex < rowCount + 1; rowIndex++) {
            // if first row, save as header
            if (rowIndex == 0) {
                header = excelSheet.getRow(rowIndex);
            } else {
                Row currentRow = excelSheet.getRow(rowIndex);
                Map<String,String> rowCells = new HashMap<>();
                String outerKey = null;
                // else, read row cells; for each cell, get corresponding header
                // and save in map
                for (int colIndex = 0; colIndex < rowCount + 1; colIndex++) {
                    if (colIndex == 0) {
                        outerKey = currentRow.getCell(colIndex).getStringCellValue();
                    } else {
                        String key = header.getCell(colIndex).getStringCellValue();
                        String cellValue = currentRow.getCell(colIndex).getStringCellValue();
                        rowCells.put(key, cellValue);
                    }
                }
                map.put(outerKey, rowCells);
            }
        }
    }

    public static String getValueFromExcel(String rowKey, String columnKey) throws IOException {
        return map.get(rowKey).get(columnKey);
    }

    public static void main(String[] args) throws IOException {

        ExcelReader reader = new ExcelReader();
        String fileName1 = "Test.xlsx";
        String sheetName1 = "employee";
        readExcel(fileName1,sheetName1);
        String firstName = getValueFromExcel("emp_A","first_name");
        String lastName = getValueFromExcel("emp_A","last_name");
        //String lastName = reader.getValueFromExcel(string,"last_name");
        String fullName = firstName + " " + lastName;
        System.out.println(fullName);
    }

}

When I read the second sheet, the row count always seems to be 1. Although when I delete the first sheet and keep only the second sheet, I am able to get the values propetly. Just cant figure out where I am making the mistake.


Below is an my second sheet in Excel.
(The first one looks the same just with different values.)

second Excel sheet

Léa Gris
  • 17,497
  • 4
  • 32
  • 41
automaticien
  • 153
  • 5
  • 14
  • 3
    You could use `for(Row row : excelSheet){for(Cell cell : row){}}` to iterate all rows and columns in the excel sheet – XtremeBaumer Sep 03 '19 at 08:22
  • this instruction stops for cycle based on rowCount? for (int colIndex = 0; colIndex < rowCount + 1; colIndex++) { – firegloves Sep 03 '19 at 08:48
  • post a representation of your second sheet please – firegloves Sep 03 '19 at 08:48
  • 4
    `int rowCount = excelSheet.getLastRowNum() - excelSheet.getFirstRowNum(); ... for (int rowIndex = 0; rowIndex < rowCount + 1; rowIndex++) { ...` is logically wrong. What if sheet's first row number is 5 and sheet's last row number is 9? Then row count is 4 and your loop goes from row 0 to row 4 but those rows are not present at all. Your loop should be `for (int rowIndex = excelSheet.getFirstRowNum(); rowIndex < excelSheet.getLastRowNum() + 1; rowIndex++) { ...`. – Axel Richter Sep 03 '19 at 08:51
  • @XtremeBaumer I tried using getting the cells inside the rows earlier but it did not work for me. – automaticien Sep 03 '19 at 09:32
  • @Axel Richter as shown in the excel file, I just want to send the name of the Key value = emp_A and column value = first_name to get the corresponding value = Xyz and so on. I am able to retrieve all rows in this particular sheet. For the other sheet, the method that I had implemented works just fine. – automaticien Sep 03 '19 at 09:32
  • https://stackoverflow.com/questions/3148535/how-to-read-excel-cell-having-date-with-apache-poi – Ng Sharma Sep 03 '19 at 09:39
  • I tested your code and it works fine using xls extension – bugsb Sep 03 '19 at 09:47
  • try to check which values you receive for first and last row. and again, this code can't work: colIndex < rowCount + 1 – firegloves Sep 03 '19 at 10:02
  • your code works fine for me with both extension, may be there is something wrong with your excel file – bugsb Sep 03 '19 at 10:09
  • I tried everything mentioned by everyone here. Still not able to figure what's wrong. Decided to move to CSV file instead of Excel – automaticien Sep 03 '19 at 13:15

0 Answers0