How can I read .xlsx and .xls files in Java?
15,804
Solution 1
Yes, you can use Apache POI to read and write xlsx and xls files.
Solution 2
If you want your code to work for both, you'll have to use the org.apache.poi.ss
package. This package has been created to unify XSSF and HSSF.
Solution 3
For one of my projects I have created a basic utility that uses Apache POI and OpenCSV and can read both xlsx, xls and csv files.
Given a converter it can convert rows to objects, like this:
RowConverter<Country> converter = (row) -> new Country(row[0], row[1]);
ExcelReader<Country> reader = ExcelReader.builder(Country.class)
.converter(converter)
.withHeader()
.csvDelimiter(';')
.sheets(1)
.build();
List<Country> list;
list = reader.read("CountryCodes.xlsx");
list = reader.read("CountryCodes.xls");
list = reader.read("CountryCodes.csv");
You may find the project on github.
Author by
Srinivas
Updated on June 06, 2022Comments
-
Srinivas about 2 years
hi i want to read xlsx file or xls file what ever it is. can XSSF support xls file ? or do i need to write the separate code for both kind of files ?
-
Srinivas over 13 yearsthank you for the reply,yes i want to write a code that should work for both xlsx ans xls.can you please give me sample code
-
Srinivas over 13 yearsorg.apache.poi.ss is working for both kind of files thank you very much
-
Valentin Rocher over 13 years@Srinivas : if your problem is solved, please mark this question as answered (the little green thing just left of my answer)
-
EpicPandaForce over 9 yearsNo need for all that, just use
WorkbookFactory.createWorkbook(InputStream)
-
Annivey over 5 yearsYou need to add (if you use maven) this dependency:
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.17</version> </dependency>
or find necessary jar-file