I have an Excel file where all my links are stored in one single column. One Link on each row. For E.g:
www.example.com
www.test.com
www.demo.com
and so on. What I want to do is visit each link and open it in Firefox. Get the link in address bar and compare it with link in excel cell. If both are same them set the string "Pass" in next cell otherwise set string "Fail". How do I do This. Can you please give me a sample code? I am using selenium web driver with java.
Here is what I tried:
try {
FileInputStream file=new FileInputStream(new File(path));
FileOutputStream outFile=new FileOutputStream(new File(path));
HSSFWorkbook workbook=new HSSFWorkbook(file);
HSSFSheet sheet=workbook.getSheetAt(0);
HSSFCell cell=null;
int s=sheet.getLastRowNum()+1;
for(int i=0; i<s; i++){
cell=sheet.getRow(i).getCell(0);
String url=cell.toString();
driver.get(url);
Thread.sleep(10000);
String urlnew=driver.getCurrentUrl().toString();
HSSFRow row=sheet.getRow(i);
HSSFCell cellresult=row.createCell(1);
if(url==urlnew){
cellresult.setCellValue("Pass");
}else{
cellresult.setCellValue("fail");
}
workbook.write(outFile);
}
file.close();
outFile.close();
}
driver = webdriver.Firefox();
Load the Excel file (you can use this)
In the rows loop, add this code: driver.get(< cell URL>);
In your code you have used the following statement to compare two strings.
if(url==urlnew)
Use the below code. it will work.
if(url.equals(urlnew))
For more information on String comparision, check this link.
Related
I have an excel book which is shared across all the business users. As part of the process, the excel needs to be updated at the server side. All users have mapped to a network drive which contains the excel book. Earlier we used to update the excel on the client side using activeX controls. Now the problem is that the path for the excel book is not accessible on the server machine and hence it's throwing file not found exception. Is there any way to handle this apart from mapping the network drive on the server machine as well?
Following is the code:
public static String updateExcelFile(String fileLocation, String dataVal,String txnId) throws IOException{
String status="";
//fileLocation = "Z:\\check.xlsx";
//FileInputStream file = new FileInputStream(new File("C:\\JXL\\Checklist OnBoarding1.1.xlsx"));
//fileLocation.rep
FileInputStream file = new FileInputStream(new File(fileLocation));
XSSFWorkbook wb = new XSSFWorkbook (file);
XSSFSheet sheet = wb.getSheetAt(0);
Row r = null;
Cell c = null;
String data[] = dataVal.split(",");
int rowCount = sheet.getPhysicalNumberOfRows();
int rowNum = rowCount;
Iterator<Row> rowInterator =sheet.iterator();
while(rowInterator.hasNext()){
r=rowInterator.next();
Iterator<Cell> cellIterator = r.cellIterator();
while(cellIterator.hasNext()){
c=cellIterator.next();
//System.out.println();
switch(c.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
System.out.print(c.getNumericCellValue() + "\t\t");
if(c.getNumericCellValue()==Integer.parseInt(txnId)){
int modRow = r.getRowNum();
System.out.println("ModRow"+modRow);
rowNum=modRow;
}
break;
case Cell.CELL_TYPE_STRING:
System.out.print(c.getStringCellValue() + "\t\t");
if(c.getStringCellValue().equals(txnId)){
int modRow = r.getRowNum();
System.out.println("ModRow"+modRow);
rowNum=modRow;
}
break;
}
}
}
if(rowNum==rowCount){
r=sheet.createRow(rowNum+1);
r=sheet.getRow(rowNum+1);
}else{
r=sheet.getRow(rowNum);
}
for(int cellNum =0; cellNum<data.length;cellNum++){
c=r.createCell(cellNum);
c.setCellValue(data[cellNum]);
}
file.close();
//FileOutputStream outFile =new FileOutputStream(new File("C:\\JXL\\Checklist OnBoarding1.1.xlsx"));
FileOutputStream outFile =new FileOutputStream(new File(fileLocation));
wb.write(outFile);
outFile.close();
status="success";
return status;
}
send the excel file to the server when the user clicks the button:
use ajax to upload the file to a servlet,
have the servlet process the file and then respond to the client with a link to the updated file (which sits in a temp folder on the server), which the ajax can then present to the user.
The user can now download the excel and put it onto the network drive, where he and other users can edit it directly.
I guess this approach would require the user to at least accept the save operation.
Also this approach does not protect you from concurrent updates on the Excel: several users can have the server edit a copy of the Excel, and several other users could directly edit the excel on the network drive.
And having the server edit the Excel might be a problem if the Excel in question is large.
Well, I think I answered the question :-).
I try to analyze excel files with links to other files and I like to know the file name and path. For that I'm using apache poi 3.14.
I figured it out for Ref3DPtg objects but for Ref3DPxg I don't know how to do it. I only get access to the cell address and the sheet name.
Does anyone know how to do it?
Code:
...
if(ptg instanceof Ref3DPxg){
cellAddress = ptg.format2DRefAsString();
sheetName = ptg.getSheetName();
workbookName = ???;
} else if(ptg instanceof Ref3DPtg) {
// by Ref3DPtg is no problem
}
Because of the way that the XLSX file format stores external references, which isn't actually =[Other.xlsx]Sheet1!A1 but actually =[23]Sheet1!A1, it's a two step process. First, get the external workbook number from the Pxg. Next, from Workbook get the ExternalLinks table for that workbook number, noting the off-by-one. (External Workbook 0 is actually the current workbook, so External Workbook 1 corresponds to External Link 0). Finally, fetch the filename for that link
So, your code should be something like:
if(ptg instanceof Ref3DPxg){
Ref3DPxg pxg = (Ref3DPxg)ptg;
int extWB = pxg.getExternalWorkbookNumber();
int extLink = extWB-1;
ExternalLinksTable links = wb.getExternalLinksTable().get(extLink);
String filename = links.getLinkedFileName();
}
I am working as java developer and i want to convert an .csv file to .xls 2003 format so that my csv will be converted into .xls file the structure of my .csv file would be like
REC_STATUS,TRADE_ID,SETTLEMENT_DATE,TRADE_EFFECTIVE_DATE,PAYMENT_TYPE,VERSION,BREAK_DOWN_BUCKET,CAUSE,NUM_CASHFLOWS_AFFECTED,PROFILE
Found only in File :B,178942690,01-Feb-16,03-Dec-14,"Coupon",5,NOISY_BREAK_BUCKET,REC_TOOL_ISSUE_PAYMENT_DIRECTION_MISMATCH | REC_TOOL_ISSUE_NOTIONAL_MISMATCH | TRADE_VERSION,1,AVS Offshore
Found only in File :B,197728700,Various,21-Dec-15,"Coupon,(x20)",2,ACTUAL DATA BREAK BUCKET,ACTUAL_DATA_BREAK,20,AVS Offshore
now i have used the open csv parser (http://opencsv.sourceforge.net/) for this and coded as shown below
CSVReader reader = new CSVReader(
new FileReader("c:/xxx.csv"), ',', '"');
// Read all rows at once
List<String[]> allRows = reader.readAll();
now please advise after reading i want to create an .xls workbook in similar fashion as .csv was created above so i have to read the values first i have to read the header and then corresponding values and have to write them in .xls 2003 format please advise how i would achieve this I am using POI 3.10 version for it
Folks please advise how to put array contents in workbook now
enter code here
class Handle
{
public static void data(List list,String path)
{
Workbook wb = new XSSFWorkbook();
HSSFSheet sheet = (HSSFSheet) wb.createSheet("Sheet");
int i=0;
while(i<list.size())
{
HSSFRow row = sheet.createRow(i);
String [] data = (String[]) list.get(i);
int j=0;
while(j<data.length)
{
HSSFCell cell = row.createCell(j);
cell.setCellValue(data[j]);
j++;
}
i++;
}
FileOutputStream fos = new FileOutputStream(path+".xls");
wb.write(fos);
fos.flush();
fos.close();
wb.close();
}
}
As told by #gagravarr you can use common SS classes to handle both ''.xls'' and ''.xlsx'' format with the same code..
In my below script, an Excel is created but failed to write the data to the sheet. Could anybody sort this out.
FileOutputStream fo = new FileOutputStream("D:\\Output.xls");
WritableWorkbook wb = Workbook.createWorkbook(fo);
WritableSheet ws = wb.createSheet("Sheet1",0);
String OutText = driver.findElement(By.xpath("gbqfqdss")).getText();
int y=0;
Label label1 = new Label(0,y,OutText);
ws.addCell(label1);
Thread.sleep(1000);
//System.out.print(OutText);
wb.write();
y++;
Thread.sleep(1000);
driver.findElement(By.id("gbqfq")).clear();
Thread.sleep(1000);
}
wb.close();
driver.quit();
With the same code, working fine in my lappy.
How you are confirming that it is not writing to excel sheet?
Mostly the cause should be "OutText" string value which is coming from getText() is null/blank value.
Try to print the value of string first & see.
Try the examples in the following link-:
http://howtodoinjava.com/2013/06/19/readingwriting-excel-files-in-java-poi-tutorial/
I am absolute new to the Eclipse Java coding. I am trying to finish a project for managing the inventory. The part i am having trouble with is that, when I tried to write the items into the excel cell, I got errors saying that the array is out of bounds.
PS: item and item.getPartname etc are all defined under another class file.
Please help. thanks
FileOutputStream os =new FileOutputStream("orderreceipt");
//Create a new workbook for writing data
HSSFWorkbook wb2 = new HSSFWorkbook();
//Create a new sheet:
HSSFSheet newsheet = wb2.createSheet("MyNewSheet");
//Create a new row:
for (int i=0; i<6; i++){
HSSFRow newrow = newsheet.createRow(i);
sentorder item = (sentorder)items.get(i);
for (short j=0; j<5; j++){
HSSFCell cell = newrow.createCell(j);
cell.setCellValue(item.getPartname());
cell.setCellValue(item.getPartnumber());
cell.setCellValue(item.getQuantity());
cell.setCellValue(new Date());
HSSFCellStyle styleOfCell = wb2.createCellStyle();
styleOfCell.setDataFormat(HSSFDataFormat
.getBuiltinFormat("m/d/yy"));
styleOfCell.setFillForegroundColor(HSSFColor.AQUA.index);
styleOfCell.setFillPattern(HSSFCellStyle.BORDER_THIN);
cell.setCellStyle(styleOfCell);
}}
wb2.write(os);
}
I can see quite a few problems with the attached code:
Missing file extension when creating new FileOutputStream - since you're generating the .xls workbook, you'd probably like to store it in the XLS file (the extension is not added automatically), also just make sure you have a proper file path to the directory you have write permissions (local application dir, as in this case should be ok though).
As already mentioned you are re-setting the same cell value 4 times
You are creating the same cell style multiple times (this is not cached behind the scenes and there is largely limited number of cells styles which can be created so if you were generating a couple thousands of rows you might get into troubles
You don't flush() and close() stream after writing your workbook. Streams in Java a precious resources which need to be manually closed.
Without stack trace it's difficult to say 100% where the ArrayOutOfBound issue you're seeing is coming from, however my guess would be that you're trying to access a item (from items collection) with the index that doesn't exist, which is a consequence that you're driving your report data from row indexes instead of the list of items you have.
Also, since you're quite new to Java a couple of guidelines which will allow you to produce hopefully better and less error-prone code in the future:
Use proper Java naming convention - please follow standard Java naming convention http://java.about.com/od/javasyntax/a/nameconventions.htm , your code will be easier to read and reason about (especially when you're looking for help from community) - i.e. sentorder class should be named as SentOrder.
Try to split your code into smaller, more testable modules i.e. you can have a helper createDataRow method called from your main method, in general having more than a couple of inner loops in one method makes them incredibly difficult to test, debug and reason about.
Unless you really need to generate .xls format, consider using XSSF* classes for generating xlsx document - it has many improvements over HSSF* (including much better dataFormat support).
Having those in mind I've rewritten your example:
public void improved(List<SentOrder> items) throws IOException {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("MyNewSheet");
HSSFCellStyle styleOfCell = workbook.createCellStyle();
styleOfCell.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy"));
styleOfCell.setFillForegroundColor(HSSFColor.AQUA.index);
styleOfCell.setFillPattern(HSSFCellStyle.BORDER_THIN);
int rowIndex = 0;
for(SentOrder item : items) {
HSSFRow row = sheet.createRow(rowIndex++);
HSSFCell nameCell = row.createCell(0);
nameCell.setCellValue(item.getPartName());
HSSFCell numberCell = row.createCell(1);
numberCell.setCellValue(item.getPartNumber());
HSSFCell quantityCell = row.createCell(2);
quantityCell.setCellValue(item.getQuantity());
HSSFCell dateCell = row.createCell(3);
dateCell.setCellValue(new Date());
dateCell.setCellStyle(styleOfCell);
}
FileOutputStream os = new FileOutputStream("order_receipt.xls");
try {
workbook.write(os);
} finally {
os.flush();
os.close();
}
}