I am trying to extract input from a external xls file into a selenium test in eclipse. I'm following a tutorial but for some reason I'm getting an error at the line:
Workbook w = Workbook.getWorkbook(fi);
I'm not sure why it's not working. Not that I'm sure why it should be working either though...
Please look at the screenshot for more info!
If you are using jxl your code is fine some thing like :
File f = new File("inputSheets\\DataDrivenJXL.xls");
Workbook w = Workbook.getWorkbook(f);
but if you are using Apache POI you will have to do something like
if(fileExtensionName.equals(".xlsx")){
Workbook = new XSSFWorkbook(inputStream);
}
else if(fileExtensionName.equals(".xls")){
Workbook = new HSSFWorkbook(inputStream);
}
Related
I have an excel template file I am retrieving from minIO, I perform some writing operation on this excel and I finally return the modified file to the user calling my code.
This flow was working fine until I tried to clone one of the sheet of my excel.
When I do that and I try to open it with Excel the file looks to be corrupted and Excel won't open it.
I am a bit lost, I am not sure what could cause this behaviour. I tried to clone an empty sheet I created for testing and it was working, so it might be related to the content of the sheet I am trying to clone but I have no idea as everything runs fine in the code.
So, theses are the part I consider relevants (getting the file from minIO, the moment I clone the sheet and finally when I write to a ByteArray)
try (InputStream inputStream = minioClient.getObject(
GetObjectArgs.builder()
.bucket("someBucket")
.object("someObject.xlsx")
.build()
)) {
Workbook workbook = new XSSFWorkbook(inputStream);
...
Sheet newSheet = workbook.cloneSheet(workbook.getSheetIndex(sheetTemplate));
workbook.setSheetName(workbook.getSheetIndex(newSheet.getSheetName()), "newName");
workbook.setSheetOrder("newName", workbook.getSheetIndex(sheetTemplate));
newSheet.getRow(10).getCell(2).setCellValue("someValue");
...
ByteArrayOutputStream bos = new ByteArrayOutputStream();
workbook.write(bos);
workbook.close();
return Optional.of(bos.toByteArray());
}
I know the question is pretty vague but maybe there is something in the way I handle this flow that it's incorrect although everything worked fine before I tried to clone some of the sheet of our template.
Any pointer would be highly appreciated.
Thank you in advance.
I use poi-3.2-FINAL-20081019.jar . Error:
Type mismatch: cannot convert from HSSFWorkbook to Workbook
try {
if (strType.equals("xls")) {
wb = new HSSFWorkbook(inputStream);
} else {
wb = new XSSFWorkbook(inputStream);
}
Sheet sheet = wb.getSheetAt(0);
How to fix it?
As the date in your jar shows - poi-3.2-FINAL-20081019.jar - you're usigng a jar that's almost 10 years old! You need to upgrade to something more modern, and at the very least something from this decade...
Right now (November 2017), the latest version is Apache POI 3.17. You can find the latest version on the Apache POI homepage, and see all the fixes in the Changelog
In addition, you should swap to using WorkbookFactory rather than looking at file extensions to work out what class to use. That hides all the detection complexity for you, works around mis-named files etc
Your code can then become the very simple
Workbook wb = WorkbookFactory.create(new File("input.xlsx"));
Sheet s = wb.getSheetAt(0);
(Use a File if you can, rather than InputStream, for lower memory)
Use newer version:
https://mvnrepository.com/artifact/org.apache.poi/poi/3.5-FINAL
Read more at: http://poi.apache.org/spreadsheet/converting.html
I created an .xlsx file using selenium through File "fil.createNewFile()", the file got created in the location but when i try to open the file i am getting a message "Excel cannot open the file 'Example.xlsx' because the file format or file extension is not valid....". Why is this happening. Please guide me to over come this problem.
Thanks in advance...
What eltabo mentioned is correct. Below is a code sample from Apache POI which will create a blank excel file.
HSSFWorkbook workbook = new HSSFWorkbook();
FileOutputStream out = new FileOutputStream(new File("C:\\new.xls"));
workbook.write(out);
out.close();
I guess you are trying something like:
File fil = new File("Example.xlsx");
fil.createNewFile();
Well, it this is your case you're creating a file with xlsx extension, but it's not truly a Excel file (it's empty). If you try to create a new file using Excel or File Explorer, you can see that a new fresh xlsx file weight about 10kb. If you need to create a Excel file you need to use Apache POI, or another library.
You need to add a sheet at least:
XSSFWorkbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet();
FileOutputStream fileOut = new FileOutputStream("Example.xlsx");
wb.write(fileOut);
fileOut.close();
PS: I use poi-ooxml, since you use a xlsx file.
Hope it helps.
I am using Apache poi for generating excel data.It works fine for all cell types except formula type cell.
The excel file with formula type cell when closed even without any changes throws a confirmatiorn like this.
For XLS fomat
http://i40.tinypic.com/126d9uw.jpg
For XLSX format:
http://i40.tinypic.com/126d9uw.jpg
Is there any way to suppress this confirmation.
I tried the below code but it didnt help.
//Workbook wb = WorkbookFactory.create(new FileInputStream(absolutexlsFileName));
FileInputStream fis = new FileInputStream(absolutexlsFileName);
Workbook wb = new XSSFWorkbook(fis);
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
evaluator.evaluateAll();
OutputStream out = msg.getHttpServletResponse().getOutputStream();
msg.getHttpServletResponse().setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
msg.getHttpServletResponse().setHeader("Expires:", "0"); // eliminates browser caching
msg.getHttpServletResponse().setHeader("Content-Disposition", "attachment; filename="+absolutexlsFileName);
wb.write(out);
out.flush();
out.close();
Looks like your formula changes would cause a cell update somewhere but you don't calculate it (but excel does and thus the change confirmation). You have to evaluate your formulas in order to prevent that warning [1]
[1] http://poi.apache.org/spreadsheet/eval.html
I am trying to open .xlsx files with POI SS with this code (taken from http://poi.apache.org/spreadsheet/quick-guide.html#ReadWriteWorkbook):
InputStream inp = new FileInputStream("workbook.xls");
//InputStream inp = new FileInputStream("workbook.xlsx");
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);
Row row = sheet.getRow(2);
Cell cell = row.getCell(3);
if (cell == null)
cell = row.createCell(3);
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue("a test");
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
and I get this error message:
Exception in thread "main" java.lang.NoClassDefFoundError: org/dom4j/DocumentException
I add the xbean.jar to my library and to my run-time libraries.
how can I resolve this exception?
Thanks !
First: Fix the Exception
There are two solutions:
As Gagravarr already mentioned: you need dom4j to fix your exception.
As Jon already mentioned: you have to update your dependencies, so you don't need dom4j anymore.
If you're using Maven, you can add the necessary dependencies with: (Maybe check for newer versions at: Maven Repository: org.apache.poi)
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.12</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
Then: Open the File
If you've fixed the exception, you can open your file.xlsx file with the following code:
String path = "Relative/Path/To/Your/File/file.xlsx";
File file = new File(path);
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(0);
// Use your sheet ...
Further tips
Like Gagravarr, I also recommend to use a file instead of a file input stream.
If you want to open a certain sheet you can use workbook.getSheet(String name);
If you don't know the relative path to your file according to your project, you can easily check it with System.out.println("Relative path: " + System.getProperty("user.dir"));
Regards, winklerrr
I haven't analyzed your error message, but after seeing the code, I see that there is something not correct.
The Wookbook is not work with *.xlsx (Office 2007 and after) files. So you have to use the XSSFWorkbook. You may want to change the wb initialization to:
XSSFWorkbook wb = (XSSFWorkbook) WorkbookFactory.create(inp);
This can help you.
InputStream is = new FileInputStream(pathOfYourXlsxFile);
XSSFWorkbook workbook = new XSSFWorkbook(is);
//Get first sheet from the workbook
XSSFSheet sheet = workbook.getSheetAt(0);
For your Exception you have to put dom4j.jar to your classpath.You can find it here
You need dom4j, that's what the exception is telling you
You might want to look at the components page on the POI website which lists the dependencies
Also, since you have a File, open directly with that, don't go via an InputStream. There's a section in the Apache POI FAQ on that, basically using a file is quicker and lower memory than buffering the whole thing via a stream!
I realize the thread is old, but it led me today to the answer I needed for the same problem.
The docs on the page suggested above (i.e include dom4j.jar) say that's no longer necessary:
"The OOXML jars used to require DOM4J, but the code has now been changed to use JAXP and no additional dom4j jars are required."
I found that including the following resolved the problem:
poi-3.11-20141221.jar
poi-ooxml-3.11-20141221.jar
poi-ooxml-schemas-3.11-20141221.jar
xmlbeans-2.6.0.jar