I want to read both xls and xlsx file format. It is working fine for xlsx format but I am getting following error while uploading xls file.
Code:
try {
FileInputStream fileInputStream = new FileInputStream("/apps/" + fileName);
//POIFSFileSystem fsFileSystem = new POIFSFileSystem(fileInputStream);
Workbook workBook = WorkbookFactory.create(OPCPackage.open(fileInputStream));
//XSSFWorkbook workBook1 = new XSSFWorkbook();
Sheet ssSheet = workBook.getSheetAt(0);
Iterator rowIterator = ssSheet.rowIterator();
while (rowIterator.hasNext()) {
Row ssRow = (Row) rowIterator.next();
Iterator iterator = ssRow.cellIterator();
List cellTempList = new ArrayList();
while (iterator.hasNext()) {
Cell ssCell = (Cell) iterator.next();
cellTempList.add(ssCell);
}
cellDataList.add(cellTempList);
}
} catch (Exception e) {
e.printStackTrace();
}
Error:
org.apache.poi.openxml4j.exceptions.InvalidFormatException: Package should contain a content type part [M1.13]
at org.apache.poi.openxml4j.opc.ZipPackage.getPartsImpl(ZipPackage.java:148)
at org.apache.poi.openxml4j.opc.OPCPackage.getParts(OPCPackage.java:623)
at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:230)
Please help.
-Thanks
I think that your problem is due to you trying to construct your workbook with the OPCPackage, even if you use WorkbookFactory. OPCPackage "unzip" your .xlsx in order to be able to read the xml files inside, but this should not work for HSSF since it is a binary file.
My recomendation would be that you use another constructor such as
WorkbookFactory.create(InputStream input)
I guess it should work fine.
Related
I am using NetBeans 14 to build a Java 8 project with Ant build. I have included:
poi-5.2.3.jar
poi-ooxml-full-5.2.3.jar
SpareseBitSet-1.2.jar
commons-codec-1.15.jar
commons-collections4-4.4.jar
commons-compress-1.2.1.jar
commons-io-2.11.0.jar
commons-math3-3.6.1.jar
curvesapi-1.0.7.jar
xml-api-1.4.0.1.jar
xmlbeans-5.1.1.jar
It builds fine. When I create a Workbook using an xls file as input it works. When I try to create a Workbook using an xlsx file it throws an exception reporting:
IO Exception processing input Bio file
java.io.IOException: Your InputStream was neither an OLE2 stream, nor an OOXML stream or you haven't provide the poi-ooxml*.jar in the classpath/modulepath - FileMagic: OOXML, having providers: [org.apache.poi.hssf.usermodel.HSSFWorkbookFactory#71a2f010]
at org.apache.poi.ss.usermodel.WorkbookFactory.wp(WorkbookFactory.java:334) ~[poi-5.2.3.jar:5.2.3]
at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:311) ~[poi-5.2.3.jar:5.2.3]
at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:277) ~[poi-5.2.3.jar:5.2.3]
at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:255) ~[poi-5.2.3.jar:5.2.3]
I've tried changing ooxml library types (-lite, -full, both, etc.).
Any help would be welcome.
I have tried sample code, working fine.
File myFile = new File("C://temp/Employee.xlsx"); FileInputStream fis = new
FileInputStream(myFile);
// Finds the workbook instance for XLSX file
XSSFWorkbook myWorkBook = new XSSFWorkbook (fis);
// Return first sheet from the XLSX workbook
XSSFSheet mySheet = myWorkBook.getSheetAt(0);
// Get iterator to all the rows in current
sheet Iterator<Row> rowIterator = mySheet.iterator();
// Traversing over each row of XLSX file
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
// For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch (cell.getCellType()) {
// Enter you code here to fetch data based on cell type
}
} System.out.println("");
}
I'm trying to create a simple Excel file in XLSX format.
I can create the old XLS files but when I try to create the other format, the file is always corrupt.
I'm using Apache POI 4.1.1.
This is my simple code:
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("new sheet");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("Hellooooo");
FileOutputStream fo = new FileOutputStream("C:/Users/Public/invoice_file/Test.xlsx");
try {
wb.write(fo);
fo.flush();
fo.close();
wb.close();
}catch (Exception e) {
e.printStackTrace();
}
And this is the error message: Error
Use
org.apache.poi.ss.usermodel.WorkbookFactory
//Parameter indicates whether you want to create an XSSF formatted file or not
WorkbookFactory.create(true); //true creates XSSF formatted file
will return you an instance of
org.apache.poi.ss.usermodel.Workbook
Then you can write to the file using
Workbook.write(OutputStream)
Solution:
try (Workbook wb = WorkbookFactory.create(true)) {
Sheet sheet = wb.createSheet("new sheet");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("Hellooooo");
try (FileOutputStream fos = new FileOutputStream("D:/Test.xlsx")) {
wb.write(fos);
}
}
How to perform different functions on Microsoft Excel spreadsheet using Apache POI ?
I'm trying to generate and update an Excel file ( data from DB ) from my Spring MVC App..
Thanks
Include apache poi jar file
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.15</version>
</dependency>
To read an excel file
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
//..
FileInputStream file = new FileInputStream(new File("C:\\test.xls"));
//Get the workbook instance for XLS file
HSSFWorkbook workbook = new HSSFWorkbook(file);
//Get first sheet from the workbook
HSSFSheet sheet = workbook.getSheetAt(0);
//Get iterator to all the rows in current sheet
Iterator<Row> rowIterator = sheet.iterator();
//Get iterator to all cells of current row
Iterator<Cell> cellIterator = row.cellIterator();
The classes we used in above code snippet, HSSFWorkbook and HSSFSheet works for .xls format. In order to work with .xlsx use XSSFWorkbook and XSSFSheet class.
Similar to HSSF, POI has different prefix for other file formats too:
HSSF (Horrible SpreadSheet Format) – reads and writes Microsoft Excel (XLS) format files.
XSSF (XML SpreadSheet Format) – reads and writes Office Open XML (XLSX) format files.
HPSF (Horrible Property Set Format) – reads “Document Summary” formation from Microsoft Office files.
HWPF (Horrible Word Processor Format) – aims to read and write Microsoft Word 97 (DOC) format files.
HSLF (Horrible Slide Layout Format) – a pure Java implementation for Microsoft PowerPoint files.
HDGF (Horrible DiaGram Format) – an initial pure Java implementation for Microsoft Visio binary files.
HPBF (Horrible PuBlisher Format) – a pure Java implementation for Microsoft Publisher files.
HSMF (Horrible Stupid Mail Format) – a pure Java implementation for Microsoft Outlook MSG files.
DDF (Dreadful Drawing Format) – a package for decoding the Microsoft Office Drawing format.
Create New Excel File
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
//..
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("FuSsA sheet");
//Create a new row in current sheet
Row row = sheet.createRow(0);
//Create a new cell in current row
Cell cell = row.createCell(0);
//Set value to new value
cell.setCellValue("Slim Shady");
try {
FileOutputStream out =
new FileOutputStream(new File("C:\\new.xls"));
workbook.write(out);
out.close();
System.out.println("Excel written successfully..");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Update Existing Excel File
try {
FileInputStream file = new FileInputStream(new File("C:\\update.xls"));
HSSFWorkbook workbook = new HSSFWorkbook(file);
HSSFSheet sheet = workbook.getSheetAt(0);
Cell cell = null;
//Update the value of cell
cell = sheet.getRow(1).getCell(2);
cell.setCellValue(cell.getNumericCellValue() * 2);
cell = sheet.getRow(2).getCell(2);
cell.setCellValue(cell.getNumericCellValue() * 2);
cell = sheet.getRow(3).getCell(2);
cell.setCellValue(cell.getNumericCellValue() * 2);
file.close();
FileOutputStream outFile =new FileOutputStream(new File("C:\\update.xls"));
workbook.write(outFile);
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
For more details, Adding Formulas and Adding Styles to Cell you can check this link: Read / Write Excel file in Java using Apache POI
For manipulation of any cells or adding formula , you can use the folowing:
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Calculate Simple Interest");
Row header = sheet.createRow(0);
header.createCell(0).setCellValue("Pricipal Amount (P)");
header.createCell(1).setCellValue("Rate of Interest (r)");
header.createCell(2).setCellValue("Tenure (t)");
header.createCell(3).setCellValue("Interest (P r t)");
Row dataRow = sheet.createRow(1);
dataRow.createCell(0).setCellValue(14500d);
dataRow.createCell(1).setCellValue(9.25);
dataRow.createCell(2).setCellValue(3d);
dataRow.createCell(3).setCellFormula("A2*B2*C2");
try {
FileOutputStream out =
new FileOutputStream(new File("C:\\formula.xls"));
workbook.write(out);
out.close();
System.out.println("Excel written successfully..");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
For adding styles to the cell,
you can use: cell.setCellStyle(style);
For adding background to cells, you can use the following:
cellStyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
Please find the Apache POI java code to read the .xls file.
FileInputStream file = new FileInputStream(new File("C:\\test.xls"));
//Get the workbook instance for XLS file
HSSFWorkbook workbook = new HSSFWorkbook(file);
while reading the .xls file using Java Apache POI, I am getting the below error in the Java Console.
java.io.IOException: Invalid header signature; read 0x6C6D783F3CBFBBEF, expected 0xE11AB1A1E011CFD0 - Your file appears not to be a valid OLE2 document
I am able to manually open the excel file without any issues. Do we have the solution to overcome this. I'm completely out of ideas so any help/pointers are greatly appreciated :)
FileInputStream fis = new FileInputStream(new File(yourpath+"/WebContent/ProductUpload.xlsx"));
XSSFWorkbook workbook = new XSSFWorkbook (fis);
int numberOfSheets = workbook.getNumberOfSheets();
for(int i=0; i < numberOfSheets; i++){
XSSFSheet sheet = workbook.getSheetAt(i);
Iterator ite = sheet.rowIterator();
while(ite.hasNext()){
Row row = (Row)ite.next();
Iterator<org.apache.poi.ss.usermodel.Cell> cite = row.cellIterator();
while(cite.hasNext()){
org.apache.poi.ss.usermodel.Cell cell = cite.next();
}
}
}
I am stuck here and tried everything to read dropdown list from .xlsx file. Please share some code which illustrate the things how Apache POI can be used
As a starting point you can try to work with getDataValidations of XSSFSheet.
XSSFWorkbook wb = null;
try {
wb = (XSSFWorkbook) WorkbookFactory.create(new FileInputStream("D:\\testWB.xlsx"));
} catch (EncryptedDocumentException | InvalidFormatException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
XSSFSheet sheet = wb.getSheetAt(0);
List<XSSFDataValidation> dataValidations = sheet.getDataValidations();
Iterator<XSSFDataValidation> iterator = dataValidations.iterator();
while(iterator.hasNext()){
XSSFDataValidation dataValidation = iterator.next();
String[] explicitListValues = dataValidation.getValidationConstraint().getExplicitListValues();
}
You have to use jExcel API. It uses Apache POI and is really easy to handle:
net.sourceforge.jexcelapi:jxl:2.6.12
you can try it.
WorkSheet sheet;
Cell comboBox = sheet.getCell(x,y);
String value= comboBox.getContents();