Skip to content

Instantly share code, notes, and snippets.

@madan712
Created October 18, 2012 14:35
Show Gist options
  • Save madan712/3912272 to your computer and use it in GitHub Desktop.
Save madan712/3912272 to your computer and use it in GitHub Desktop.
Read / Write Excel file (.xls or .xlsx) using Apache POI
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
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;
public class ReadWriteExcelFile {
public static void readXLSFile() throws IOException
{
InputStream ExcelFileToRead = new FileInputStream("C:/Test.xls");
HSSFWorkbook wb = new HSSFWorkbook(ExcelFileToRead);
HSSFSheet sheet=wb.getSheetAt(0);
HSSFRow row;
HSSFCell cell;
Iterator rows = sheet.rowIterator();
while (rows.hasNext())
{
row=(HSSFRow) rows.next();
Iterator cells = row.cellIterator();
while (cells.hasNext())
{
cell=(HSSFCell) cells.next();
if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING)
{
System.out.print(cell.getStringCellValue()+" ");
}
else if(cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC)
{
System.out.print(cell.getNumericCellValue()+" ");
}
else
{
//U Can Handel Boolean, Formula, Errors
}
}
System.out.println();
}
}
public static void writeXLSFile() throws IOException {
String excelFileName = "C:/Test.xls";//name of excel file
String sheetName = "Sheet1";//name of sheet
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet(sheetName) ;
//iterating r number of rows
for (int r=0;r < 5; r++ )
{
HSSFRow row = sheet.createRow(r);
//iterating c number of columns
for (int c=0;c < 5; c++ )
{
HSSFCell cell = row.createCell(c);
cell.setCellValue("Cell "+r+" "+c);
}
}
FileOutputStream fileOut = new FileOutputStream(excelFileName);
//write this workbook to an Outputstream.
wb.write(fileOut);
fileOut.flush();
fileOut.close();
}
public static void readXLSXFile() throws IOException
{
InputStream ExcelFileToRead = new FileInputStream("C:/Test.xlsx");
XSSFWorkbook wb = new XSSFWorkbook(ExcelFileToRead);
XSSFWorkbook test = new XSSFWorkbook();
XSSFSheet sheet = wb.getSheetAt(0);
XSSFRow row;
XSSFCell cell;
Iterator rows = sheet.rowIterator();
while (rows.hasNext())
{
row=(XSSFRow) rows.next();
Iterator cells = row.cellIterator();
while (cells.hasNext())
{
cell=(XSSFCell) cells.next();
if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING)
{
System.out.print(cell.getStringCellValue()+" ");
}
else if(cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC)
{
System.out.print(cell.getNumericCellValue()+" ");
}
else
{
//U Can Handel Boolean, Formula, Errors
}
}
System.out.println();
}
}
public static void writeXLSXFile() throws IOException {
String excelFileName = "C:/Test.xlsx";//name of excel file
String sheetName = "Sheet1";//name of sheet
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet(sheetName) ;
//iterating r number of rows
for (int r=0;r < 5; r++ )
{
XSSFRow row = sheet.createRow(r);
//iterating c number of columns
for (int c=0;c < 5; c++ )
{
XSSFCell cell = row.createCell(c);
cell.setCellValue("Cell "+r+" "+c);
}
}
FileOutputStream fileOut = new FileOutputStream(excelFileName);
//write this workbook to an Outputstream.
wb.write(fileOut);
fileOut.flush();
fileOut.close();
}
public static void main(String[] args) throws IOException {
writeXLSFile();
readXLSFile();
writeXLSXFile();
readXLSXFile();
}
}
@gabykant
Copy link

gabykant commented Aug 30, 2018

This code has a problem and I am trying to solve. If your have a file with multiple lines (my case 10000) it throws an exception java.lang.OutOfMemoryError: Java heap space
I use this to solve my problem https://github.com/monitorjbl/excel-streaming-reader

@shilpaluthra
Copy link

How can we get value from readXLSFile class , that can be used as Input for another test case.

@raphy78626
Copy link

Trying to use the Workbook wb = WorkbookFactory.create(new File(fileName)); // Read the xls file found on the below link

Tried some other libraries jxcel, no luck, Can someone help if am doing anything wrong

XLS files : https://www.huduser.gov/portal/datasets/excel/wy_foreclosure.zip

Code:

import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
.......
......

try (InputStream is = new FileInputStream(new File(fileName));
Workbook wb = WorkbookFactory.create(new File(fileName));) {

    }

Exception Trace :

Exception in thread "main" org.apache.poi.util.RecordFormatException: Not enough data (0) to read requested (2) bytes
at org.apache.poi.hssf.record.RecordInputStream.checkRecordPosition(RecordInputStream.java:243)
at org.apache.poi.hssf.record.RecordInputStream.readShort(RecordInputStream.java:262)
at org.apache.poi.hssf.record.PrintSetupRecord.(PrintSetupRecord.java:74)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.apache.poi.hssf.record.RecordFactory$ReflectionConstructorRecordCreator.create(RecordFactory.java:84)
at org.apache.poi.hssf.record.RecordFactory.createSingleRecord(RecordFactory.java:345)
at org.apache.poi.hssf.record.RecordFactoryInputStream.readNextRecord(RecordFactoryInputStream.java:288)
at org.apache.poi.hssf.record.RecordFactoryInputStream.nextRecord(RecordFactoryInputStream.java:254)
at org.apache.poi.hssf.record.RecordFactory.createRecords(RecordFactory.java:494)
at org.apache.poi.hssf.usermodel.HSSFWorkbook.(HSSFWorkbook.java:344)
at org.apache.poi.hssf.usermodel.HSSFWorkbookFactory.createWorkbook(HSSFWorkbookFactory.java:49)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.poi.ss.usermodel.WorkbookFactory.createWorkbook(WorkbookFactory.java:314)
at org.apache.poi.ss.usermodel.WorkbookFactory.createHSSFWorkbook(WorkbookFactory.java:292)
at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:128)
at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:74)
at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:281)
at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:253)
at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:234)
at com.noteunlimited.util.ForeClosureDump.generateStatistics(ForeClosureDump.java:55)
at com.noteunlimited.util.ForeClosureDump.main(ForeClosureDump.java:64)

@raphy78626
Copy link

Tried same on the python libs

import xlrd
loc = "~/Downloads/IL_County.xls"
wb = xlrd.open_workbook(loc)
WARNING *** file size (38194) not 512 + multiple of sector size (512)
WARNING *** OLE2 inconsistency: SSCS size is 0 but SSAT size is non-zero
sheet = wb.sheet_by_index(0)
sheet.cell_value(0, 0)
u'countycode'
sheet.cell_value(1, 0)
u'17001'
Everything just works fine

@Madhuri98
Copy link

i get errror
java.lang.BootstrapMethodError: Exception from call site #3 bootstrap method
at org.apache.poi.openxml4j.opc.PackagePartCollection.(PackagePartCollection.java:47)
at org.apache.poi.openxml4j.opc.ZipPackage.getPartsImpl(ZipPackage.java:245)
at org.apache.poi.openxml4j.opc.OPCPackage.getParts(OPCPackage.java:726)
at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:304)
at org.apache.poi.ooxml.util.PackageHelper.open(PackageHelper.java:37)
at org.apache.poi.xssf.usermodel.XSSFWorkbook.(XSSFWorkbook.java:303)
at com.jsonconvertor.utilities.ReadWriteExcelFile.readXLSXFile(ReadWriteExcelFile.java:53)
at com.jsonconvertor.MainActivity$3.onClick(MainActivity.java:87)
at android.view.View.performClick(View.java:6597)
at android.view.View.performClickInternal(View.java:6574)
at android.view.View.access$3100(View.java:778)
at android.view.View$PerformClick.run(View.java:25885)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.ClassCastException: Bootstrap method returned null

@samuelmugi
Copy link

This is great. But It's better to use a WorkbookFactory to create a Workbook instance. This way, you won't need to use format specific classes like HSSFWorkbook and XSSFWorkbook and your program will work for both .xls and .xlsx files without writing separate methods.

private void readExcelFile(filePath) {
    Workbook workbook = WorkbookFactory.create(new File(filePath));
    Sheet sheet = workbook.getSheetAt(0);
    DataFormatter dataFormatter = new DataFormatter();
    sheet.forEach(row -> {
        row.forEach(cell -> {
            String cellValue = dataFormatter.formatCellValue(cell);
            System.out.print(cellValue + "\t");
        });
        System.out.println();
    });
}

The complete code can be found at The CalliCoder Blog.

i think this is the best way to read both xls and xlsx. Thanks

@pnramya
Copy link

pnramya commented Aug 9, 2019

I am using this apache POI for reading excel sheet data. one of the column has numbers as string and need to remove the space after the string.But trim(), replaceAll() is not working for the data coming from the excel sheet.

Example : currentcell.getStringCellValue().trim() is also not working.It is returning the same string with the white space. Even tried with the replaceAll().

Can anybody please help me with this ?
Thank you in advance.

@sunil-singh-chaudhary
Copy link

@bibekkumar005 may be this is you needed:

<!-- POI : Excel library -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>${poi.version}</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>${poi.version}</version>
</dependency>

please write the dependency .....having trouble when including POI jars for hssf and xssf

how to add this in android studio Dependency

@dineshr93
Copy link

How to convert .xls to .xlsx and vice versa?

@whdals0
Copy link

whdals0 commented May 4, 2020

Try it for Gradle Dependency in Android Studio:

implementation group: 'org.apache.poi', name: 'poi-ooxml', version: '3.9'

Thank you.

After changing the gradle version everything worked fine.

@anupdey99
Copy link

Any luck with android studio? .xls works fine but .xlsx giving me a lots to error.
Any one with working solution for .xlsx generation?

Dependency
implementation 'org.apache.poi:poi:3.9'
implementation 'org.apache.poi:poi-ooxml:3.9'
implementation 'org.apache.xmlbeans:xmlbeans:2.3.0'

@nitish8879
Copy link

Try it for Gradle Dependency in Android Studio:

implementation group: 'org.apache.poi', name: 'poi-ooxml', version: '3.9'

hello I implemnet latest version of but it' throw an error while I run app
Here is the Error
#1.Failed to transform bcprov-jdk15on-1.68.jar
#2.Unsupported class file major version 59

@nitish8879
Copy link

Any luck with android studio? .xls works fine but .xlsx giving me a lots to error.
Any one with working solution for .xlsx generation?

Dependency
implementation 'org.apache.poi:poi:3.9'
implementation 'org.apache.poi:poi-ooxml:3.9'
implementation 'org.apache.xmlbeans:xmlbeans:2.3.0'

Try it for Gradle Dependency in Android Studio:

implementation group: 'org.apache.poi', name: 'poi-ooxml', version: '3.9'

hello I implemnet latest version of but it' throw an error while I run app
Here is the Error
#1.Failed to transform bcprov-jdk15on-1.68.jar
#2.Unsupported class file major version 59

@nitish8879
Copy link

anybody here please share me the right dependancy to implemeant in anroid studio

@gabrielarg
Copy link

when the line of the file is big enough,the code running below is very slow!

FileOutputStream outputStream = new FileOutputStream(outFile);
xssfWorkbook.write(outputStream);
outputStream.flush();
outputStream.close();

@rashibhardwaj
Copy link

Hi
My code is running fine on local but on server it gives the given error, I am using apache poi 4.1.2, unable to debug and reproduce this

2021-07-07T14:18:52.477042302ZException in thread "pool-48-thread-1" java.lang.InternalError: java.lang.reflect.InvocationTargetException at java.desktop/sun.font.FontManagerFactory$1.run(FontManagerFactory.java:86) at java.base/java.security.AccessController.doPrivileged(Native Method) at java.desktop/sun.font.FontManagerFactory.getInstance(FontManagerFactory.java:74) at java.desktop/java.awt.Font.getFont2D(Font.java:497) at java.desktop/java.awt.Font.canDisplayUpTo(Font.java:2250) at java.desktop/java.awt.font.TextLayout.singleFont(TextLayout.java:469) at java.desktop/java.awt.font.TextLayout.(TextLayout.java:530) at org.apache.poi.ss.util.SheetUtil.getDefaultCharWidth(SheetUtil.java:273) at org.apache.poi.ss.util.SheetUtil.getColumnWidth(SheetUtil.java:248) at org.apache.poi.ss.util.SheetUtil.getColumnWidth(SheetUtil.java:233) at org.apache.poi.xssf.usermodel.XSSFSheet.autoSizeColumn(XSSFSheet.java:555) at org.apache.poi.xssf.usermodel.XSSFSheet.autoSizeColumn(XSSFSheet.java:537) at com.haulerhero.crm.data.service.ExportService.createCell(ExportService.java:118) at com.haulerhero.crm.data.service.ExportService.writeHeaderLine(ExportService.java:105) at com.haulerhero.crm.data.service.ExportService$1.run(ExportService.java:49) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) at java.base/java.lang.Thread.run(Thread.java:829) Caused by: java.lang.reflect.InvocationTargetException at java.base/jdk.internal.reflect.GeneratedConstructorAccessor151.newInstance(Unknown Source) at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490) at java.desktop/sun.font.FontManagerFactory$1.run(FontManagerFactory.java:84) ... 17 more Caused by: java.lang.NullPointerException at java.desktop/sun.awt.FontConfiguration.getVersion(FontConfiguration.java:1262) at java.desktop/sun.awt.FontConfiguration.readFontConfigFile(FontConfiguration.java:225) at java.desktop/sun.awt.FontConfiguration.init(FontConfiguration.java:107) at java.desktop/sun.awt.X11FontManager.createFontConfiguration(X11FontManager.java:719) at java.desktop/sun.font.SunFontManager$2.run(SunFontManager.java:379) at java.base/java.security.AccessController.doPrivileged(Native Method) at java.desktop/sun.font.SunFontManager.(SunFontManager.java:324) at java.desktop/sun.awt.FcFontManager.(FcFontManager.java:35) at java.desktop/sun.awt.X11FontManager.(X11FontManager.java:56) ... 21 more

@ChandrasekarPerumal
Copy link

If flush() used right after write(f) no data is been updated to the file. Why so?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment