I'm trying to update an existing Excel file. I used the code I saw here Writing to an Existing Excel File but I can't call the function from the main activity.
I tried to create a instance from the department.
It is my code of the class
public class ExceLJxL {
public ExceLJxL(){
}
public static void WriteFile(String path) throws BiffException, IOException, RowsExceededException, WriteException {
Workbook wb = Workbook.getWorkbook(new File(path));
WritableWorkbook copy = Workbook.createWorkbook(new File("D:\temp.xls"), wb);
WritableSheet sheet = copy.getSheet(1);
WritableCell cell;
Label l = new Label(1, 1, "");
cell = (WritableCell) l;
sheet.addCell(cell);
copy.write();
copy.close();
wb.close();
}
}
And here I call the function
ExceLJxL exceLJxL= new ExceLJxl();
exceLJxL.WriteFile( "path");
But he doesn't know it
Related
How to write data in the excel sheet by using java selenium? , below code is for reading data from excel sheet
After reading data from excel sheet and executing in the website is fine but,
Need: After execution, I want to "WRITE" the status in the excel sheet.
In my library code: 1)how to write code for write data in excel sheet?
2)How to retrive numeric value from excel sheet
below is my code---------------------
package demo1;
public class Exceldriven
{
WebDriver driver;
#Test(dataProvider="website")
public void FAHT(String firstnametest, String lastnametest, String Email String Password) //throws Exception
{ System.setProperty("webdriver.chrome.driver","D:\\selenium\\drivers\\chromedriver_win32\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("https://www.*****************.com");
Thread.sleep(2000);
driver.findElement(By.xpath("//input[#name='txtFirstName']")).sendKeys(firstnametest);
driver.findElement(By.xpath("//input[#name='txtLastName']")).sendKeys(lastnametest);
driver.findElement(By.xpath("//input[#name='txtEmailID']")).sendKeys(Email);
driver.findElement(By.xpath("//input[#name='txtPhone']")).sendKeys(Phonenumber);
}
#DataProvider(name="website")
public Object[][] passdata() throws Exception
{
Exceldata c1=new Exceldata("D:\\New folder (2)\\Testdata1.xlsx");
int rows=c1.getrowcount(0);
Object[][] data=new Object[rows][3];
for(int i=0;i<rows;i++)
{
data[i][0]=c1.getdata(0,i,0);
data[i][1]=c1.getdata(0,i,1);
data[i][2]=c1.getdata(0,i,2);
data[i][3]=c1.getdata(0,i,3);
}
return data;
}
}
below is my library code----------------------
public class Exceldata
{
XSSFWorkbook wb;
XSSFSheet FAHT;
public Exceldata(String excelpath) throws Exception
{
try
{
File src=new File(excelpath);
FileInputStream fis=new FileInputStream(src);
wb=new XSSFWorkbook(fis);
}
catch (Exception e)
{
System.out.print(e.getMessage());
}
}
public String getdata(int Sheetnumber,int row,int column)
{
FAHT=wb.getSheetAt(Sheetnumber);
String data= FAHT.getRow(row).getCell(column).getStringCellValue();
return data;
}
public int getrowcount(int sheetIndex)
{
int row = wb.getSheetAt(sheetIndex).getLastRowNum();
row=row+1;
return row;
}
}
Example on how to write in Row 0, Column 0:
FileInputStream fileInputStream = new FileInputStream(file);
XSSFWorkbook workbook = new XSSFWorkbook(fileInputStream);
Sheet sheet = workbook.getSheet("Sheet1");
sheet.setColumnWidth(0, 1000);
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("YourText");
FileOutputStream fileOutputStream = new FileOutputStream(file);
workbook.write(new FileOutputStream(file));
fileInputStream.close();
fileOutputStream.close();
I want to read Excel sheet from specific row number and only want some specific columns value. I tried lots of stuff, but I don't get proper output as expected.
Below is my code snippet:
public class ReadExcel {
File src=new File("F:\\ucd\\UAT_Patch_31012018.xlsx");
XSSFWorkbook wb;
XSSFSheet Sheet1;
FileOutputStream fileOut;
public void ReadExcel1() throws Exception{
FileInputStream fis = new FileInputStream(src);
XSSFWorkbook wb=new XSSFWorkbook(fis);
XSSFSheet Sheet1=wb.getSheetAt(0);
int rowcount=Sheet1.getPhysicalNumberOfRows();
int colcount=Sheet1.getRow(0).getPhysicalNumberOfCells();
for(int i=6;i<=9;i++){
for(int j=0;j<=rowcount;j++){
String testdata1=Sheet1.getRow(i).getCell(j).getStringCellValue();
System.out.println(testdata1);
}
}
}
public static void main(String args[]) throws Exception{
ReadExcel read=new ReadExcel();
read.ReadExcel1();
}
}
Excel file format:
File Name Target Server Target Path
abc/Abc.txt 10.0.43.101 /home/urbancode/UrbanCode/Test/DeployableComponent/abc
pqr/Abc.txt /home/urbancode/UrbanCode/Test/DeployableComponent/pqr
xyz/Abc.txt /home/urbancode/UrbanCode/Test/DeployableComponent/xyz
I want to save my output in temp.txt file as below:
abc/Abc.txt;/home/urbancode/UrbanCode/Test/DeployableComponent/abc
pqr/Abc.txt;/home/urbancode/UrbanCode/Test/DeployableComponent/pqr
Can some one please provide codes/logic to retrieve Excel (.xlsx) data. I need the data to be retrieved in such a way that I can get the value and pass it any where in code for testing web page. This is the code how I need to get:
driver.findElement(By.id("")).sendkeys(getExceldata(row, column));
I just need to define the row and column and it should get the data from Excel sheet by using any method like getExceldata(1,2)
public String cellValue(String filepath,String sheetname,int r,int c)
{
try{
FileInputStream fis = new FileInputStream(new File(filepath));
book = WorkbookFactory.create(fis);
sh = book.getSheet(sheetname);
System.out.println(sh.getSheetName());
row = sh.getRow(r);
cell = row.getCell(c);
return cell.getStringCellValue();
}catch(Exception e)
{
return null;
}
}
public int getRows(String filepath,String sheetname)
{
try{
FileInputStream fis= new FileInputStream(filepath);
book= new XSSFWorkbook(fis);
return book.getSheet(sheetname).getLastRowNum();
}
catch(Exception e)
{
return 0;
}
----------------------------New class below--------------------------------
WebDriver driver;
Excel excel= new Excel();
public static String filepath="D:\\Chinmaya Work\\Work Space\\simpleProject\\src\\Newcustomerdata.xlsx";
public static String sheetname="newcusotomer";
public void setUp() throws InterruptedException
{
driver=new FirefoxDriver();
driver.get("http://www.demo.guru99.com/V4/index.php");
Thread.sleep(5000);
}
public void loginToApplication()
{
Homepagegurru99 home=new Homepagegurru99(driver);
home.enterUsername("mngr45812");
home.enterPassword("chinu#221");
home.clickLoogin();
driver.manage().timeouts().implicitlyWait(60,TimeUnit.SECONDS);
}
public void gotoNewcustomepage()
{
Dashbardgurru99 dash=new Dashbardgurru99(driver);
dash.gotonewCustomerpage();
driver.manage().timeouts().implicitlyWait(60,TimeUnit.SECONDS);
}
public void createNewcustomer()
{
Newcustomeradd create=new Newcustomeradd(driver);
int rowCount=excel.getRows(filepath, sheetname);
System.out.println(rowCount);
create.eneterCustomername(excel.cellValue(filepath, sheetname, 2,0));
create.selectSex();
create.enterDob(excel.cellValue(filepath, sheetname, 3,0));
create.enterAddress(excel.cellValue(filepath, sheetname, 4,0));
create.enterCity(excel.cellValue(filepath, sheetname, 5,0));
create.enterState(excel.cellValue(filepath, sheetname, 6,0));
create.enterPin(excel.cellValue(filepath, sheetname, 7,0));
create.enterMobileno(excel.cellValue(filepath, sheetname, 8,0));
create.enterEmail(excel.cellValue(filepath, sheetname, 9,0));
create.enterPassword(excel.cellValue(filepath, sheetname, 10,0));
create.clickSubmit();
driver.manage().timeouts().implicitlyWait(60,TimeUnit.SECONDS);
driver.switchTo().alert().accept();
}
public void logOut()
{
driver.findElement(By.linkText("Log out")).click();
driver.manage().timeouts().implicitlyWait(60,TimeUnit.SECONDS);
driver.switchTo().alert().accept();
driver.close();
}
Dependencies (poi-ooxml.jar)
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
To Persist into an Excel File
fis = new FileInputStream(new File(fileName));
XSSFWorkbook workbook = new XSSFWorkbook (fis);
XSSFSheet sheet = workbook.getSheetAt(0);
XSSFRow row1 = sheet.createRow(0);
XSSFCell r1c1 = row1.createCell(0);
r1c1.setCellValue("Demo");
fis.close();
FileOutputStream fos = new FileOutputStream(new File(outputFile));
workbook.write(fos);
fos.close();
To Retrieve from an Excel File follow the link, Get Cell Value from Excel Sheet with Apache Poi .
HTH
I am playing around with the jexcel libary
I have tried to code a small program which does the following:
Read an xls File
Make some computaitons in the sheet and write it to another place
public class DataProcessor {
private String inputFile;
private String outputFile;
private Sheet sheet;
private Workbook w;
public void setInputFile(String inputFile) {
this.inputFile = inputFile;
}
public void setOutputFile(String outputFile) {
this.outputFile = outputFile;
}
public void read() throws IOException {
File inputWorkbook = new File(inputFile);
Workbook w;
try {
w = Workbook.getWorkbook(inputWorkbook);
sheet = w.getSheet(0);
} catch (BiffException e) {
e.printStackTrace();
}
}
#SuppressWarnings("deprecation")
public void write() throws IOException, WriteException {
File file = new File(inputFile);
WorkbookSettings wbSettings = new WorkbookSettings();
wbSettings.setLocale(new Locale("en", "EN"));
WritableWorkbook workbook = Workbook.createWorkbook(file, wbSettings);
workbook.createSheet("Lolonator", 0);
workbook.createSheet("Lolonator123", 1);
workbook.copy(w);
workbook.write();
workbook.close();
}
public static void main(String[] args) throws IOException, WriteException {
ReadExcel test = new ReadExcel();
test.setInputFile("C:/Users/Desktop/sheet1.xls");
test.read();
System.out.println("####################################################");
System.out.println("File read!");
// Write
System.out.println("####################################################");
System.out.println("Start to write the file!");
WriteExcel out = new WriteExcel();
out.setOutputFile("C:/Users/Desktop/sheet2.xls");
out.write();
System.out.println("Please check the result file!");
}
}
However, this does not work. I do not get any output in my sheet, even though my program runs without exception to the end. I really appreciate your answer!!!
In your write function, you are using "inputFile" as parameter to File constructor but you are not initializing it after you create the out object.
So the following line in the write function
File file = new File(inputFile);
should be
File file = new File(outputFile);
Also are you sure that you do not see any errors after running this code. It should be throwing a null pointer exception.
Hope this helps...
Can someone point me in the right direction for writing to an excel file in java??
I am not understanding the links I found online.
Could you just send me a link or anything which I could follow through??
Thank you,
J
Another alternative to Apache POI is the JExcelAPI, which (IMO) has an easier to use API. Some examples:
WritableWorkbook workbook = Workbook.createWorkbook(new File("output.xls"));
WritableSheet sheet = workbook.createSheet("First Sheet", 0);
Label label = new Label(0, 2, "A label record");
sheet.addCell(label);
Number number = new Number(3, 4, 3.1459);
sheet.addCell(number);
Not to be banal, but Apache POI can do it. You can find some code examples here:
http://poi.apache.org/spreadsheet/examples.html
Posting useful examples for API's.
Step by step example for using JExcelAPI:
http://www.vogella.de/articles/JavaExcel/article.html
http://www.java-tips.org/other-api-tips/jexcel/how-to-create-an-excel-file.html
Step by step example for using POI (little old one but useful):
http://www.javaworld.com/javaworld/jw-03-2004/jw-0322-poi.html
Here i'm going to give sample example,how to write excel;use this in pom.xml
<dependency>
<groupId>net.sf.jxls</groupId>
<artifactId>jxls-core</artifactId>
<version>0.9</version>
</dependency>
Model class:
public class Products {
private String productCode1;
private String productCode2;
private String productCode3;
constructors,setters and getters
}
main class:
public class WriteExcel {
public void writeExcel() {
Collection staff = new HashSet();
staff.add(new Products("101R15ss0100", "PALss Kids 1.5 A360 ", "321"));
staff.add(new Products("101R1ss50100", "PAL sKids 1.5 A360 ", "236"));
Map beans = new HashMap();
beans.put("products", staff);
XLSTransformer transformer = new XLSTransformer();
try {
transformer.transformXLS(templateFileName, beans, destFileName);
System.out.println("Completed!!");
} catch (ParsePropertyException e) {
System.out.println("In ParsePropertyException");
e.printStackTrace();
} catch (IOException e) {
System.out.println("In IOException");
e.printStackTrace();
}
}
public static void main(String[] args) {
WriteExcel writeexcel = new WriteExcel();
writeexcel.writeExcel();
}
}
public class ExcelUtils {
private static XSSFSheet ExcelWSheet;
private static XSSFWorkbook ExcelWBook;
private static XSSFCell Cell;
private static XSSFRow Row;
File fileName = new File("C:\\Users\\satekuma\\Pro\\Fund.xlsx");
public void setExcelFile(File Path, String SheetName) throws Exception {
try {
FileInputStream ExcelFile = new FileInputStream(Path);
ExcelWBook = new XSSFWorkbook(ExcelFile);
ExcelWSheet = ExcelWBook.getSheet(SheetName);
} catch (Exception e) {
throw (e);
}
}
public static String getCellData(int RowNum, int ColNum) throws Exception {
try {
Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
String CellData = Cell.getStringCellValue();
return CellData;
} catch (Exception e) {
return "";
}
}
public static void setCellData(String Result, int RowNum, int ColNum, File Path) throws Exception {
try {
Row = ExcelWSheet.createRow(RowNum - 1);
Cell = Row.createCell(ColNum - 1);
Cell.setCellValue(Result);
FileOutputStream fileOut = new FileOutputStream(Path);
ExcelWBook.write(fileOut);
fileOut.flush();
fileOut.close();
} catch (Exception e) {
throw (e);
}
}
}
Here is the basic code to write data in excel file (.xls).
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
public class Export2Excel {
public static void main(String[] args) {
try {
//create .xls and create a worksheet.
FileOutputStream fos = new FileOutputStream("D:\\data2excel.xls");
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet worksheet = workbook.createSheet("My Worksheet");
//Create ROW-1
HSSFRow row1 = worksheet.createRow((short) 0);
//Create COL-A from ROW-1 and set data
HSSFCell cellA1 = row1.createCell((short) 0);
cellA1.setCellValue("Sno");
HSSFCellStyle cellStyle = workbook.createCellStyle();
cellStyle.setFillForegroundColor(HSSFColor.GOLD.index);
cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
cellA1.setCellStyle(cellStyle);
//Create COL-B from row-1 and set data
HSSFCell cellB1 = row1.createCell((short) 1);
cellB1.setCellValue("Name");
cellStyle = workbook.createCellStyle();
cellStyle.setFillForegroundColor(HSSFColor.LIGHT_CORNFLOWER_BLUE.index);
cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
cellB1.setCellStyle(cellStyle);
//Create COL-C from row-1 and set data
HSSFCell cellC1 = row1.createCell((short) 2);
cellC1.setCellValue(true);
//Create COL-D from row-1 and set data
HSSFCell cellD1 = row1.createCell((short) 3);
cellD1.setCellValue(new Date());
cellStyle = workbook.createCellStyle();
cellStyle.setDataFormat(HSSFDataFormat
.getBuiltinFormat("m/d/yy h:mm"));
cellD1.setCellStyle(cellStyle);
//Save the workbook in .xls file
workbook.write(fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
NOTE: You need to download jar library from the link: http://www.java2s.com/Code/JarDownload/poi/poi-3.9.jar.zip
I've used Apache's POI Library when I've had to write to excel files from Java. I found it rather straight forward once you get the hang of it. Java World has a good tutorial about starting out using POI that I found very helpful.