How to Read XLSX File in Java Using apache Poi API

Here we will implement the code to read XLSX file using apache POI API :
and download required jars based on below snapshot






Code : -


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.test.XLS;

import java.io.*;
import java.util.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;

/**
 *
 * @author anand
 */
public class XLSReader {

    static final String fileName = "FriendsZone.xlsx";
    FileInputStream file = null;

    public void readXLSFile() {
        try {
            file = new FileInputStream(new File(fileName));

            XSSFWorkbook workbook = new XSSFWorkbook(file);

            XSSFSheet sheet = workbook.getSheetAt(0);

            Iterator<Row> rowIterator = sheet.iterator();

            while (rowIterator.hasNext()) {

                Row row = rowIterator.next();

                Iterator<Cell> cellIterator = row.cellIterator();

                while (cellIterator.hasNext()) {

                    Cell cell = cellIterator.next();

                    switch (cell.getCellType()) {
                        case Cell.CELL_TYPE_NUMERIC:

                            System.out.print(cell.getNumericCellValue() + "\t");

                            break;

                        case Cell.CELL_TYPE_STRING:

                            System.out.print(cell.getStringCellValue() + "\t");

                            break;
                    }
                }

                System.out.println("");
            }

            file.close();

        } catch (Exception e) {

            e.printStackTrace();

        } finally {

            if (file != null) {

                try {

                    file.close();

                } catch (IOException ex) {

                    //Logger.getLogger(XLSReader.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }

    public static void main(String[] args){
     
            new XLSReader().readXLSFile();
         
     
    }
}



For any Doubt please comment it . Thanks 

Comments

Popular posts from this blog

Converting JSONArray into CSV file in java

Java Design pattern

Map class field to map