Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (13.1k points)
Can anyone help me how I can able to read and write an excel file using Java with 3 columns and n number of rows? Any help would be appreciated.

1 Answer

0 votes
by (26.7k points)

You can use the Apache POI HSSF service to read and write the excel content in Java. Given below is the code, you can take it as a reference:

try {

    POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(file));

    HSSFWorkbook wb = new HSSFWorkbook(fs);

    HSSFSheet sheet = wb.getSheetAt(0);

    HSSFRow row;

    HSSFCell cell;

    int rows; // No of rows

    rows = sheet.getPhysicalNumberOfRows();

    int cols = 0; // No of columns

    int tmp = 0;

    // This trick ensures that we get the data properly even if it doesn't start from first few rows

    for(int i = 0; i < 10 || i < rows; i++) {

        row = sheet.getRow(i);

        if(row != null) {

            tmp = sheet.getRow(i).getPhysicalNumberOfCells();

            if(tmp > cols) cols = tmp;

        }

    }

    for(int r = 0; r < rows; r++) {

        row = sheet.getRow(r);

        if(row != null) {

            for(int c = 0; c < cols; c++) {

                cell = row.getCell((short)c);

                if(cell != null) {

                    // Your code here

                }

            }

        }

    }

} catch(Exception ioe) {

    ioe.printStackTrace();

}

I hope this will help.

Want to become a Java Expert? Join Java Training now!!

Want to know more about Java? Watch this video on Java Course | Java Tutorial for Beginners:

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...