File update followed by file upload in Selenium with java - java

I have a scenario where first I update an excel column with certain values using one test case (test case 1) and then use that file for upload in the next test case (test case 2). I am able to successfully update the file and also able to browse the file for upload. the problem is that the content is not being read from the file. I just have to open the excel file created and perform the save action manually and then when I run the test (test case 2)related to uploading it works perfectly fine. I am not sure what is causing the issue. it would be of great help if someone can support this issue.
Here are the test steps
Update file column values - code snippet
public void setColValues(String fileName, String sheetName, int colIndex, List<Integer> sData) {
try {
String excelPath = System.getProperty("director to file path");
FileInputStream fis = new FileInputStream(excelPath);
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sh = workbook.getSheet(sheetName);
int rowCount = sh.getLastRowNum();
logger.info(rowCount);
int index = 0;
for (int rowCounter = 2; rowCounter <= rowCount; rowCounter++) {
sh.getRow(rowCounter).getCell(colIndex).setCellValue(sData.get(index));
index++;
}
fis.close();
FileOutputStream fos = new FileOutputStream(new File(excelPath), false);
workbook.write(fos);
workbook.close();
fos.close();
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
go to a specific URL
Click the browse button and pass the file path
Click the button to upload

It might be because you are not passing a File instance to FileInputStream constructor?
You wrote:
FileInputStream fis = new FileInputStream(excelPath);
Try instead:
FileInputStream inputStream = new FileInputStream(new File(excelPath));

Related

how to solve - Getting OLE2 exception while opening .xls excel file using selenium+java

Hello All
Hey,it's omkaar as a software tester(Automation Selenium+Java).
There is a scinario of reading excel file using Automation (selenium+java)which having .xls (Microsoft Excel 97-2003 Worksheet) file extension.
Now i am not able to read excel file due to the error/popup massege(Please have look attched screenshot) which is obsereved while opening that file manually.
Steps which i have followed to read excel file.
Created object of file class and give the refference of that perticular file.
Created workbook instance.
Created sheet, row and cell instance.
Used "for each loop" to iterate through each cell to get the data.
(You can also go through attached code.)
here is my code.
public class WorkWithXLSFile extends BaseTest {
public static void main(String[] args) {
try {
File file = new File("C:\\Users\\Omkar Shrotri\\Downloads\\Ticketdetails.xls");
if (file.exists()) {
FileInputStream fis = new FileInputStream(file);
HSSFWorkbook wb = new HSSFWorkbook(fis);
HSSFSheet sheet1 = wb.getSheetAt(0);
DataFormatter formatter11 = new DataFormatter();
for (int i = 0; i <= 7; i++) {
String excel_data = formatter11.formatCellValue(sheet1.getRow(2).getCell(i));
// int s = i+1;
String web_data = driver.findElement(By.xpath("//table/tbody/tr[1]/td['" + i + "']")).getText();
if (excel_data.equals(web_data)) {
System.out.println("Passed");
}
}
}
} catch (Exception NotOLE2FileException) {
System.out.print(NotOLE2FileException);
// handle popup
// try code
}
}
}

Rename the file if exists instead of overwriting it

When I execute below code it overwrite the existing file. I want to keep old file and new file too. What can be done here? Can we rename it like Test(1).xlsx, Test(2).xlsx, Test(3).xlsx like windows pattern?
File excel = new File("C:\\TEST\\Test.xlsx");
try (FileInputStream fis = new FileInputStream(excel);
XSSFWorkbook book = new XSSFWorkbook(fis);) {
..
..
..
try (FileOutputStream outputStream = new FileOutputStream("C:\\TEST\\Output\\Test.xlsx")) {
book.write(outputStream);
}
}
You can check if the file already exists using the exists() method before you start writing to it.
If the file already exists, write to a different file.
File excel = new File(determineFileName());
try (FileInputStream fis = new FileInputStream(excel);
XSSFWorkbook book = new XSSFWorkbook(fis);) {
...
}
with
private String determineFileName(){
String path = "C:\\TEST\\Test.xlsx";
int counter = 0;
while(new File(path).exists()){
counter++;
path = "C:\\TEST\\Test(" + counter + ").xlsx";
}
return path;
}

Force close an excel file before writing to it

I am writing to an existing excel file using Java, say this is fileA. (I'm using APACHE POI for this.)
It is possible that the excel fileA is opened by someone. It is saved in a shared folder accessed by a lot of people.
I want to avoid encountering
java.io.FileNotFoundException: (The process cannot access the file
because it is being used by another process)
Because no matter if the existing excel file is opened or not, I need to save the output of my Java app.
Upon researching, I think it is impossible to close fileA (opened by some other process/user, not by my Java App) within my Java code.
What I'm doing now is to create a new excel file, say fileB if fileA is currently opened. I'm using the code below.
File file = null;
FileOutputStream out = null;
int workbookNo = 0;
do{
String append = "";
if(workbookNo != 0){
append = "_Copy" + Integer.toString(workbookNo);
}
file = new File(filePath + "ValidateLock_" + dataDate + append + ".xlsx");
try{
out = new FileOutputStream(file);
workbookNo = 0;
}catch(FileNotFoundException e){
//e.printStackTrace();
workbookNo++;
}
}while(workbookNo != 0);
However, I'm getting the error below.
org.apache.poi.openxml4j.exceptions.NotOfficeXmlFileException: No
valid entries or contents found, this is not a valid OOXML (Office
Open XML) file
try like this :
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);
//Close the excel input file (inputstream)
file.close();
FileOutputStream outFile =new FileOutputStream(new File("C:\\update.xls"));
workbook.write(outFile);
//Close output excel file
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

Getting error "Your InputStream was neither an OLE2 stream, nor an OOXML stream" when created file through apache POI

I am trying to check if my excel file already exists. If it doesn't exists, I want to create a new one and if it exists I will delete it and create a new one. I wrote following program but I am getting error at line - workbook= WorkbookFactory.create(instream);
The error is->
java.lang.IllegalArgumentException: Your InputStream was neither an OLE2 stream, nor an OOXML stream
at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:89)
at tryIng.main(tryIng.java:84)
Here is a program ->
try {
String filePath= "C:/Users/pritik/Desktop/t1.xlsx";
File file = new File(filePath);
filePath= file.getAbsolutePath();
xlFile = new File(filePath);
if(xlFile.exists() && !xlFile.isDirectory())
xlFile.delete(); //delete if file already exists.
xlFile.createNewFile();
inStream = new FileInputStream(xlFile);
workbook = WorkbookFactory.create(inStream); // I get error at this line
String sheetName="NewSheet";
Sheet sheet = workbook.createSheet(sheetName);
FileOutputStream fOut = new FileOutputStream(xlFile);
int i,j;
xRows = xTS.length;
xCols = xTS[0].length;
for(i =0;i<xRows;i++)
{
row = sheet.createRow(i);
for(j=0;j<xCols;j++)
{
cell = row.createCell(j);
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue(xTS[i][j]);
}
}
workbook.write(fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Don't create an empty file and try to read it, that won't work. An empty zero byte file is not valid, and can't be loaded Instead, have POI create an new file for you, which you will write later.
Change the code:
if(xlFile.exists() && !xlFile.isDirectory())
xlFile.delete(); //delete if file already exists.
xlFile.createNewFile();
inStream = new FileInputStream(xlFile);
workbook = WorkbookFactory.create(inStream);
To instead be:
if(xlFile.exists() && !xlFile.isDirectory())
xlFile.delete(); //delete if file already exists.
if (xlFile.toString().endsWith(".xls") {
workbook = new HSSFWorkbook();
} else {
workbook = new XSSFWorkbook();
}
Also, if you do want to read an existing file, don't use a stream if you have a file! See this bit of the POI docs for why not.

make specific path on Excel POI

I want to make a path that saved in database.
here's my code.
#RequestMapping("import_excel")
#ResponseBody
public Map<String, ? extends Object> import_excel() {
modelMap.clear();
try {
HttpSession session = req.getSession();
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("Export");
Row row1 = sheet.createRow((short) 3);
row1.createCell(0).setCellValue("Asset Number");
row1.createCell(1).setCellValue("Asset Barcode");
row1.createCell(2).setCellValue("Asset Name");
short i = 4;
Row row2 = sheet.createRow(i++);
row2.createCell(0).setCellValue(as.getCdas());
row2.createCell(1).setCellValue(as.getBcd());
row2.createCell(2).setCellValue(as.getNm());
FileOutputStream fileOut = new FileOutputStream(src + "/Export.xls");
wb.write(fileOut);
fileOut.close();
modelMap.put("success", true);
modelMap.put("rows", obj);
modelMap.put("count", count);
} catch (IOException ex) {
modelMap.put("success", false);
modelMap.put("msg", ex.getMessage());
}
return modelMap;
}
I want to make FileOutputStream fileOut = new FileOutputStream(src + "/Export.xls"); with the path I save in db. so If I want to change the path I just change in db.
I've tried code above but doesnt seems work.
please help me. Thanks :)
I would suggest that use it programmatically...
use
String PathTillProject = System.getProperty("user.dir");
This will give you the system path one level up to src i.e. till your project (I assume your src is just within your project directory). For example if your project name is TestProject then location or src is TestProject/src. Now you can use it like:
String PathTillProject = System.getProperty("user.dir");
FileOutputStream fileOut = new FileOutputStream(PathTillProject + "/src/Export.xls");

Categories