JAVA Code to Create an Excel File in Relative Path

Using excel files is one of the most common method for test data and other types of data management. The java code to create an Excel file is very easy and most of the code is self explanatory. Lets have a look at the same:
 
Eclipse needs to be pointed to the required JAR files in order to make it work with various functions provided by apache. Read more on Apache at it’s official website: Apache POI

 

The poi(s) need to be added to the project before running this code. Different versions may or may not support all functions and need to be worked with accordingly. Below is the snapshot of POI(s) used in my program. They can be downloaded from https://poi.apache.org/download.html#archive

Eclipse - Java Build Path
Eclipse-Java Build Path

 

Below is the JAVA class which creates an excel file in the “Relative Path”.

The code first checks for the directory “temp” at the relative path and creates if it does not exists.

Next, the excel file with three columns namely – “First Name”, “Last Name” and “Country”. If the file already exists, the code overwrites the same.

The code prints following on console when run the first time:
Directory already exists!
relativePath:tempMyExcelFile.xlsx
Excel File created: C:FunctionalTestAutomationproject_TestProject1tempMyExcelFile.xlsx
When we run the code second time, the console is as below:
Directory already exists!
relativePath:tempMyExcelFile.xlsx
Excel File created: C:FunctionalTestAutomationproject_TestProject1tempMyExcelFile.xlsx

Tada! That was one of the ways to write JAVA code and create an Excel file at the relative path. Hope it helped.

Apache POIXML Exception: InvalidFormatException:Package should contain a content type part [M1.13]

Problem:
I received following error while using “Apache POI(XSSF API)” for reading xlsx file”.
Exception occurred during playback of script [TC002_Login] [CRFCN0019E: RationalTestScriptException on line 45 of script TC002_Login – org.apache.poi.POIXMLException: org.apache.poi.openxml4j.exceptions.InvalidFormatException: Package should contain a content type part [M1.13].].
Below is the error displayed in log file:
  • exception_name = org.apache.poi.POIXMLException
  • exception_message = org.apache.poi.openxml4j.exceptions.InvalidFormatException: Package should contain a content type part [M1.13]
  • script_name = TC002_Login
  • script_id = TC002_Login.java
  • line_number = 45
exception_stack = at org.apache.poi.util.PackageHelper.open(PackageHelper.java:41)
at org.apache.poi.xssf.usermodel.XSSFWorkbook.(XSSFWorkbook.java:204)
at SuperHelperClass.SuperScriptHelperlibrary.updateExcelReportScriptname(SuperScriptHelperlibrary.java:1018)
at TC002_Login.testMain(TC002_Login.java:45)

at org.eclipse.equinox.internal.app.EclipseAppContainer.callMethodWithException(EclipseAppContainer.java:587)
at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:198)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:380)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:235)
at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:648)
at org.eclipse.equinox.launcher.Main.basicRun(Main.java:603)
at org.eclipse.equinox.launcher.Main.run(Main.java:1465)
at org.eclipse.equinox.launcher.Main.main(Main.java:1438)
at org.eclipse.core.launcher.Main.main(Main.java:34)
at org.apache.poi.openxml4j.opc.ZipPackage.getPartsImpl(ZipPackage.java:178)
at org.apache.poi.openxml4j.opc.OPCPackage.getParts(OPCPackage.java:662)
at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:269)
at org.apache.poi.util.PackageHelper.open(PackageHelper.java:39)
Line number 45 read:
updateExcelReportScriptname(DestReport); //DestReport is a string variable with path+filename
The function ‘updateExcelReportScriptname’ is defined as below:
public void updateExcelReportScriptname(String DestReport)
{
                        FileInputStream file;
                        try {
                                    file = new FileInputStream(DestReport);
                                    XSSFWorkbook workbook;
                                    try {
                                                workbook = new XSSFWorkbook(file); //Line NUmber 1018
                                                XSSFSheet mySheet1 = workbook.getSheetAt(0);
                                                XSSFRow myRow1 = null;
                                                XSSFCell myCell1 = null;
                                                XSSFCellStyle style = workbook.createCellStyle();
                                                style.setAlignment(CellStyle.ALIGN_JUSTIFY);
                                                style.setFillPattern(CellStyle.SOLID_FOREGROUND);
                                                style.setBorderBottom(CellStyle.BORDER_THIN);
                                                style.setBorderTop(CellStyle.BORDER_THIN);
                                                style.setBorderRight(CellStyle.BORDER_THIN);
                                                style.setBorderLeft(CellStyle.BORDER_THIN);
                                                style.setWrapText(true);
                                                String excelData1[][] = new String[500][500];
                                                int row = mySheet1.getPhysicalNumberOfRows();
                                                excelData1[row][0] = getScriptName();
                                                myRow1 = mySheet1.createRow(row);
                                                myCell1 = myRow1.createCell(0);
                                                myCell1.setCellValue(excelData1[row][0]);
                                                style.setFillForegroundColor(IndexedColors.LIGHT_YELLOW.getIndex());
                                                myCell1.setCellStyle(style);
                                                for(int cellNum = 1; cellNum <= 19; cellNum++)
                                                {
                                                            XSSFCell myCell = null; 
                                                            myCell = myRow1.createCell(cellNum);
                                                            myCell.setCellValue(“”);
                                                }
                                                file.close();       
                                                FileOutputStream outFile =new FileOutputStream(DestReport); 
                                                workbook.write(outFile);  
                                                outFile.close();
                                    } catch (IOException e) {
                                                // TODO Auto-generated catch block
                                                e.printStackTrace();
                                    }   
                        } catch (FileNotFoundException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                        }
            }
Solution:
There are two reasons I could analyse which may cause this error:
1. When I try to read ‘.xls’ file with my code and for ‘.xlsx’ files. There are different classes for xls and xlsx files namely:
Classes to be used for XLS file: HSSFWorkbook & HSSFSheet
Classes to be used for XLSX file: XSSFSheet & XSSFSheet
Required one must be used accordingly.
2. Sometimes, the same error is thrown even when the correct file format is used. The reason for this could be any of the below:
  • File is password protected
  • File is corrupted. For me, this was the case and I realized it when I tried to open the file and got bellow error. 

Microsoft Excel Error for Corrupt File
 Hope this helps solve the problem.