I am trying to read a .xlsx Excel file but I am getting an exception:
Error in getting data from excel Invalid header signature; read
1688935826934608, expected -2226271756974174256
What is the thing that I am missing?
My code is
FileInputStream fileInputStream;
try {
fileInputStream = new FileInputStream(filePath + "\\"
+ "uploadAreaExcel.xlsx");
HSSFWorkbook workbook;
workbook = new HSSFWorkbook(fileInputStream);
HSSFSheet worksheet = workbook.getSheet("Sheet1");
System.out.println("Total Count :"
+ Integer.toString(worksheet.getLastRowNum()));
for(int i=1;i<worksheet.getLastRowNum();i++){
HSSFRow row1 = worksheet.getRow(i);
HSSFCell cellA1 = row1.getCell((short) 0);
System.out.println(cellA1.getStringCellValue());
HSSFCell cellB1 = row1.getCell((short) 1);
System.out.println(cellB1.getStringCellValue());
}
} catch (Exception e) {
System.out.println("Error in getting data from excel "+e.getMessage());
}
Ok, now I see that you are using HSSF to handle .xlsx file. But HSSF doesn't support .xlsx, you should give a try to XSSF workbook.
Related
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 save symbols like 🔥🔥 to xlsx file using Java 8 and Apache POI library?
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Sheet 1");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("\uD83D\uDD25\uD83D\uDD25");
try {
FileOutputStream outputStream = new FileOutputStream("text.xlsx");
workbook.write(outputStream);
workbook.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
As a result, I get a file with symbols "????" Instead of "🔥🔥".
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 have removed a lot of code, mainly try-catch blocks and pasted here what I believe would be easy for you to look at and advise me on resolving the issue I am facing. I am running the below script in a Groovy Script step in SoapUI tool. Most of the variable datatypes are following the Groovy language syntax.
When I run this code, a xlsx file with file name mentioned in the destPath variable is created but with a size of 0 KB. When I try to open the file, I am seeing the message "Excel cannot open the file "filename" because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file." I could not see where I am making mistake.
def srcPath = "C:\\Test Data\\Test Data2.xlsx"
def destPath = "C:\\Test Data\\Results\\destSheet.xlsx"
def setData = new SetData(log,srcPath,destPath)
log.info setData.setCellData("Result",0,"Testing123")
class SetData{
def log; //log variable to print values on the console
String srcPath;
String destPath;
XSSFWorkbook workbook;
OPCPackage pkg;
SetData(log,srcPath,destPath){
this.log = log;
this.srcPath =srcPath;
this.destPath = destPath}
public String setCellData(String colName,int rowNum, String data){
OPCPackage pkg = OPCPackage.open(srcPath);
Workbook workbook = WorkbookFactory.create(pkg);
if(rowNum<0)
return "false";
int colNum=-1;
XSSFSheet sheet = workbook.getSheetAt(0);
XSSFRow row=sheet.getRow(0);
for(int i=0;i<row.getLastCellNum();i++){
if(row.getCell(i).getStringCellValue().trim().equals(colName))
colNum=i;
}
sheet.autoSizeColumn(colNum);
row = sheet.getRow(rowNum+1);
log.info "Row data " + row //log.info is equivalent to System.out.Println
in Java,to print values on the console.
XSSFCell cell = row.getCell(colNum);
// cell style
CellStyle cs = workbook.createCellStyle();
cs.setWrapText(true);
cell.setCellStyle(cs);
log.info data; //prints Testing123
cell.setCellValue(data); // Set the cell data
log.info "raw cell Value" + "***" +
cell.getRichStringCellValue().getString() //Prints "Testing123"
log.info "Column index "+ cell.getColumnIndex() // Prints 3
log.info cell.getRowIndex() // Prints 0
fileOut = new FileOutputStream(new File(destPath));
workbook.write(fileOut);
fileout.flush();
fileOut.close();
fileOut=null;
pkg.close()
return "true";
}
Looks like your mixing XSSFWorkbook and Workbook. You should also check to see if the rows and cells you're reading from your source file actually have those rows/cells and create them if they don't. Here's a simplified version of your code for creating an Excel workbook from another workbook and writing to it:
String srcPath = "C:\\projects\\source.xlsx";
String destPath = "C:\\projects\\destSheet.xlsx";
XSSFWorkbook workbook = (XSSFWorkbook)WorkbookFactory.create(new File(srcPath));
XSSFSheet sheet = workbook.getSheetAt(0);
XSSFRow row = sheet.getRow(1);
if(row == null) { row = sheet.createRow(1); }
XSSFCell cell = row.getCell(0);
if(cell == null) { cell = row.createCell(0); }
cell.setCellValue("Testing123");
FileOutputStream fileOut = new FileOutputStream(new File(destPath));
workbook.write(fileOut);
fileOut.flush();
fileOut.close();
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.