Write captured data to Excel using java - java

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/

Related

What is causing excel to crash after updating file thru java?

I have some java code that opens an excel sheet, adds auto filter to a group of columns, then saves and closes. The problem is that when a user opens the file and trys to sort smallest to largest or largest to smallest excel will freeze then crash. But if you first filter then you can sort with out issue and it does not freeze and crash.
private static void AddFilter()
{
//Adds filter to the rows in Column 2
try
{
FileInputStream fileIn = new FileInputStream("C:\\Users\\gria\\Desktop\\Fleet Manager Summary.xls");
HSSFWorkbook report = new HSSFWorkbook(fileIn);
Sheet sheet = report.getSheetAt(0);
sheet.setAutoFilter(CellRangeAddress.valueOf("A5:P5"));
FileOutputStream fileOut = new FileOutputStream("C:\\Users\\gria\\Desktop\\Fleet Manager SummaryT.xls");
report.write(fileOut);
fileOut.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
Thank you,
UPDATE:
After some experimenting I have updated the info and code since the original question was asked to better explain the problem.
Try changing
XSSFFormulaEvaluator.evaluateAllFormulaCells(report);
to
HSSFFormulaEvaluator.evaluateAllFormulaCells(report);
XSSFFormulaEvaluator.evaluateAllFormulaCells() works for XSSfWorkbook, but not for the HSSFWorkbook.
Documentation
Also,
you can edit your commented code to:
for(int i = 5; i < sheet.getLastRowNum(); i++)
{
Cell cell = sheet.getRow(i).getCell(6);
//I don't know if you have data in all of the cells,
//So I suggest you to evaluate null
if(cell != null && !cell.getStringCellValue().isEmpty())
{
cell.setCellValue(Double.valueOf(cell.getStringCellValue()).doubleValue());
}
}

While reading the data from output excel,it shows error in selenium webdriver

FileInputStream f2 = new FileInputStream("D:\\Screenshot\\test_grid.xls");
Workbook CPT_check =Workbook.getWorkbook(f2);
Sheet c1=CPT_check.getSheet(0);
String CPT_check_final =c1.getCell(2,7).getContents();
if(Final_result==CPT_check_final)
System.out.println("CPT " +Final_result+" is correct");
else
System.out.println("CPT " +Final_result+" is not correct");
This is my code and when I run it, it shows error as
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
at jxl.read.biff.SheetImpl.getCell(SheetImpl.java:318)
at login.Login_first.main(Login_first.java:135)
The scenario is I write the data in excel using my code and from the same excel i need to read the data. So i tried my above code. it shows error. PLease help me out of this.
You can try the following code to get the content of the cell
FileInputStream f2 = new FileInputStream("D:\\Screenshot\\test_grid.xls");
Workbook CPT_check =Workbook.getWorkbook(f2);
Sheet c1=CPT_check.getSheet(0);
for(int rows=0;rows<c1.getRows();rows++)
{
for(int cols=0;cols<c1.getColumns();cols++)
{
System.out.println(c1.getCell(cols, rows).getContents().trim());
}
}

POI - Excel remains held by some process and cannot be edited

I am using POI to read,edit and write excel files.
My process flow is like write an excel, read it and again write it.
Then if I try to edit the file using normal desktop excel application while my Java app is still running, the excel cannot be saved, it says some process is holding the excel,
I am properly closing all file handles.
Please help and tell me how to fix this issue.
SXSSFWorkbook wb = new SXSSFWorkbook(WINDOW_SIZE);
Sheet sheet = getCurrentSheet();//stores the current sheet in a instance variable
for (int rowNum = 0; rowNum < data.size(); rowNum++) {
if (rowNum > RECORDS_PER_SHEET) {
if (rowNum % (RECORDS_PER_SHEET * numberOfSheets) == 1) {
numberOfSheets++;
setCurrentSheet(wb.getXSSFWorkbook().createSheet());
sheet = getCurrentSheet();
}
}
final Row row = sheet.createRow(effectiveRowCnt);
for (int columnCount = 0; columnCount < data.get(rowNum).size(); columnCount++) {
final Object value = data.get(rowNum).get(columnCount);
final Cell cell = row.createCell(columnCount);
//This method creates the row and cell at the given loc and adds value
createContent(value, cell, effectiveRowCnt, columnCount, false, false);
}
}
public void closeFile(boolean toOpen) {
FileOutputStream out = null;
try {
out = new FileOutputStream(getFileName());
wb.write(out);
}
finally {
try {
if (out != null) {
out.close();
out = null;
if(toOpen){
// Open the file for user with default program
final Desktop dt = Desktop.getDesktop();
dt.open(new File(getFileName()));
}
}
}
}
}
The code looks correct. After out.close();, there shouldn't be any locks left.
Things that could still happen:
You have another Java process (for example hanging in a debugger). Your new process tries to write the file, fails (because of process 1) and in the finally, it tries to open Excel which sees the same problem. Make sure you log all exceptions that happen in wb.write(out);
Note: The code above looks correct in this respect, since it only starts Excel when out != null and that should only be the case when Java could open the file.
Maybe the file wasn't written completely (i.e. there was an exception during write()). Excel tries to open the corrupt file and gives you the wrong error message.
Use a tool like Process Explorer to find out which process keeps a lock on a file.
I tried all the options. After looking thoroughly, it seems the problem is the Event User model.
I am using the below code for reading the data:
final OPCPackage pkg = OPCPackage.open(getFileName());
final XSSFReader r = new XSSFReader(pkg);
final SharedStringsTable sst = r.getSharedStringsTable();
final XMLReader parser = fetchSheetParser(sst);
final Iterator<InputStream> sheets = r.getSheetsData();
while (sheets.hasNext()) {
final InputStream sheet = sheets.next();
final InputSource sheetSource = new InputSource(sheet);
parser.parse(sheetSource);
sheet.close();
}
I assume the excel is for some reason held by this process for some time. If I remove this code and use the below code:
final File file = new File(getFileName());
final FileInputStream fis = new FileInputStream(file);
final XSSFWorkbook xWb = new XSSFWorkbook(fis);
The process works fine an the excel does not remain locked.
I figured it out actually.
A very simple line was required but some some reason it was not explained in the New Halloween Document (http://poi.apache.org/spreadsheet/how-to.html#sxssf)
I checked the Busy Developer's Guide and got the solution.
I needed to add
pkg.close(); //To close the OPCPackage
This added my code works fine with any number of reads and writes on the same excel file.

Visit links from excel file using selenium web driver

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.

Apache POI throwing IOException when reading XLSX workbook

I'm trying to get the following code to run and am getting an IOException:
String cellText = null;
InputStream is = null;
try {
// Find /mydata/myworkbook.xlsx
is = new FileInputStream("/mydata/myworkbook.xlsx");
is.close();
System.out.println("Found the file!");
// Read it in as a workbook and then obtain the "widgets" sheet.
Workbook wb = new XSSFWorkbook(is);
Sheet sheet = wb.getSheet("widgets");
System.out.println("Obtained the widgets sheet!");
// Grab the 2nd row in the sheet (that contains the data we want).
Row row = sheet.getRow(1);
// Grab the 7th cell/col in the row (containing the Plot 500 English Description).
Cell cell = row.getCell(6);
cellText = cell.getStringCellValue();
System.out.println("Cell text is: " + cellText);
} catch(Throwable throwable) {
System.err.println(throwable.getMessage());
} finally {
if(is != null) {
try {
is.close();
} catch(IOException ioexc) {
ioexc.printStackTrace();
}
}
}
The output from running this in Eclipse is:
Found the file!
Stream Closed
java.io.IOException: Stream Closed
at java.io.FileInputStream.readBytes(Native Method)
at java.io.FileInputStream.read(FileInputStream.java:236)
at java.io.FilterInputStream.read(FilterInputStream.java:133)
at java.io.PushbackInputStream.read(PushbackInputStream.java:186)
at java.util.zip.ZipInputStream.readFully(ZipInputStream.java:414)
at java.util.zip.ZipInputStream.readLOC(ZipInputStream.java:247)
at java.util.zip.ZipInputStream.getNextEntry(ZipInputStream.java:91)
at org.apache.poi.openxml4j.util.ZipInputStreamZipEntrySource.<init>(ZipInputStreamZipEntrySource.java:51)
at org.apache.poi.openxml4j.opc.ZipPackage.<init>(ZipPackage.java:83)
at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:267)
at org.apache.poi.util.PackageHelper.open(PackageHelper.java:39)
at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:204)
at me.myorg.MyAppRunner.run(MyAppRunner.java:39)
at me.myorg.MyAppRunner.main(MyAppRunner.java:25)
The exception is coming from the line:
Workbook wb = new XSSFWorkbook(is);
According to the XSSFWorkbook Java Docs this is a valid constructor for an XSSFWorkbook object, and I don't see anything "jumping out" at me to indicate that I'm using my InputStream incorrectly. Can any POI gurus help spot where I'm going awrye? Thanks in advance.
The problem is simple:
is = new FileInputStream("/mydata/myworkbook.xlsx");
is.close();
You are closing your output stream before passing it to the constructor and it cannot be read.
Simply delete the is.close() here to fix the issue, as it will be cleaned up in the finally statement at the end.
you are closing the stream is.close();
and then using it, don't close it until you have used it.
As the others have pointed out, you are closing your InputStream which is breaking things
However, you really shouldn't be using an InputStream in the first place! POI uses less memory when given the File object directly rather than going through an InputStream.
I'd suggest you have a read through the POI FAQ on File vs InputStream, then change your code to be:
OPCPackage pkg = OPCPackage.open(new File("/mydata/myworkbook.xlsx"));
Workbook wb = new XSSFWorkbook(pkg);

Categories