Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excel file reading in Java(Simple JSP and Servlet) [closed]

Tags:

java

jsp

servlets

how to read an Excel sheet in java without treating it as a database, and without using any other external api's.

like image 781
abson Avatar asked Nov 25 '25 06:11

abson


1 Answers

There is no direct way to deal with Excel sheet in Java. You should use Apache POI Java API.

Apache POI is a Java library for reading and writing various Microsoft file formats, especially Office related ones, based on OLE2 and OOXML, such as XLS and DOCX.

Let's see one example of reading an Excel sheet. It supports for both xls and xlsx file format.

import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

private Vector importExcelSheet(String fileName)
{
    Vector cellVectorHolder = new Vector();
    try
    {
        Workbook workBook = WorkbookFactory.create(new FileInputStream(fileName));
        Sheet sheet = workBook.getSheetAt(0);
        Iterator rowIter = sheet.rowIterator();

        while(rowIter.hasNext())
        {
            XSSFRow row = (XSSFRow) rowIter.next();
            Iterator cellIter = row.cellIterator();
            Vector cellStoreVector=new Vector();

            while(cellIter.hasNext())
            {
                XSSFCell cell = (XSSFCell) cellIter.next();
                cellStoreVector.addElement(cell);
            }
            cellVectorHolder.addElement(cellStoreVector);
        }
    }
    catch (Exception e)
    {
        System.out.println(e.getMessage());
    }
    return cellVectorHolder;
}

Call the above method which will return a Vector as follows.

Vector dataHolder=importExcelSheet("Excel_file.xlsx");

Note : the Vector used here is just for a demonstration. One should not use it, since it is obsolete in Java. Use other types of Collections available in the Java Collection framework.

like image 58
Lion Avatar answered Nov 27 '25 18:11

Lion



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!