Issue with inserting string into excel sheet - java

I am trying to create an excel file which can have value as name and ID
The lines which have made bol are giving me error in my program.Kindly help me out as what might be the mistake... pls
If possible also help me out with the code of only writing name as in string into the excel file.
package demos;
import jxl.*;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import java.io.*;
import java.util.*;
import com.sun.rowset.internal.Row;
import jxl.CellView;
import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.biff.RowsExceededException;
public class StringInp
{
public static void main(String[] args) throws IOException
{
try
{
String filename="C:\\virclipse\\input.xls";
WritableWorkbook wb=Workbook.createWorkbook(new File(filename));
//Create a blank sheet
WritableSheet sheet = wb.createSheet("Employee Data",0);
//This data needs to be written (Object[])
Map<String, Object[]> data = new TreeMap<String, Object[]>();
data.put("1", new Object[] {"ID", "NAME"});
data.put("2", new Object[] {101, "Shivany"});
data.put("3", new Object[] {102, "Nalini"});
data.put("4", new Object[] {103, "John"});
data.put("5", new Object[] {104, "Ayush"});
//Iterate over data and write to sheet
Set<String> keyset = data.keySet();
int rownum = 0;
for (String key : keyset)
{
***Row row = sheet.createRow(rownum++);***
Object [] objArr = data.get(key);
int cellnum = 0;
for (Object obj : objArr)
{
***Cell cell = row.createCell(cellnum++);***
if(obj instanceof String)
{
***cell.setCellValue((String)obj);***
}
else if(obj instanceof Integer)
{
***cell.setCellValue((Integer)obj);***
}
}
//Write the workbook in file system
FileOutputStream out = new FileOutputStream(new File("filename"));
wb.write();
wb.close();
}
}
catch(WriteException e)
{
System.out.println("there is an error");
}
}
}

You are using the right imports but you need to have the required jxml jars in your build path also.

you can read here, what is jExcel API here is a tutorial also you can download API from here please download jexcelapi_2_6_12.zip, after downloading extract it and put jxl.jar in your build path, those errors should go then

Related

How to get names containing particular Character in Java?

I have a workbook in which I have multiple tabs now I want to read all the tabs name and return the tab name containing particular character in it , in my case its data
example assumpition is :-
Expected tabsname - > welcome_data.xslx , hello_value.xslx;
output -> welcome_data.xslx
Any help is appreciated ,
code which I was trying was :- I was able to get the tabs name but how to filter it .
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class EXcelsheet {
public static void main(String[] args) throws IOException {
String xlsxFile = "/home/working/git/ui_spec.xlsx";
FileInputStream file = new FileInputStream(new File(xlsxFile));
XSSFWorkbook workbook = new XSSFWorkbook(file);
System.out.println("number of sheet::" + workbook.getNumberOfSheets());
List<String> sheetNames = new ArrayList<String>();
for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
sheetNames.add(workbook.getSheetName(i));
}
}
}
I don't get the issue.
Does replacing
sheetNames.add(workbook.getSheetName(i));
with
String sheetName = workbook.getSheetName(i);
if (sheetName.contains(<char>)
{
sheetNames.add(workbook.getSheetName(i));
}
not work?

Why I am getting Data Provider MisMatch error when I try to read from excel file?

I am trying to do data driven testing and I am not able to figure it out why I am getting data mismatch. I am trying to automate just usernames and that is in form of string. Can you please review my code and tell me what I am doing wrong?
Below are two files. one is my main method file and one is my excel config file. I have also attached screenshot of my error. Any help would be appreciated. Thank you.
File1:
`
package loginAdmin;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class PersonateUser {
#Test(dataProvider="testdata")
public void login(String username) throws InterruptedException
{
System.setProperty("webdriver.chrome.driver",
C:\\Users\\abc\\Downloads\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().deleteAllCookies();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(200, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(200, TimeUnit.SECONDS);
driver.get("www.abc.com/AdminHome.aspx");
driver.findElement(By.id("M_layout_content_PCDZ_MW2NO7V_ctl00_webInputForm_txtLoginName")).
sendKeys("admin");
driver.findElement(By.id("M_layout_content_PCDZ_MW2NO7V_ctl00_webInputForm_txtPassword")).
sendKeys("Password");
driver.findElement(By.id("M_layout_content_PCDZ_MW2NO7V_ctl00_webInputForm_cmdContinue")).
click();
driver.findElement(By.id("M_layout_content_PCDZ_M5QH8YG_ctl00_lblUserName")).
click();
driver.findElement(By.id("M_layout_content_PCDZ_M5QH8YG_ctl00_txtUserName")).
sendKeys(username);
driver.findElement(By.id("M_layout_content_PCDZ_M5QH8YG_ctl00_btnSearch")).click();
driver.findElement(By.id("M_layout_content_PCDZ_M5QH8YG_ctl00_resultsGrid_ctl02_LogInAsUser")).
click();
System.out.println("User is able to login successfully");
driver.findElement(By.xpath("/html/body/form/div[3]/div[3]/div[1]/div[1]/div/div[5]/ul/li[6]/a")).
click();
#DataProvider(name="testdata")
public Object[][] TestDataFeed()
{
ReadExcelFile config = new
ReadExcelFile("C:\\Users\\abc\\eclipseworkspace\\Login\\testdata\\testdata.xlsx");
int rows = config.getRowCount(0);
Object[][] credentials = new Object[rows][2];
for(int i = 0; i < rows; i++)
{
credentials[i][0] = config.getData(0, i, 0);
}
return credentials;
}
}
`
File 2:
` package loginAdmin;
import java.io.File;
import java.io.FileInputStream;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ReadExcelFile
{
XSSFWorkbook wb;
XSSFSheet sheet;
public ReadExcelFile(String excelPath)
{
try
{
File src = new File(excelPath);
FileInputStream fis = new FileInputStream(src);
wb =new XSSFWorkbook(fis);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
public String getData(int sheetnumber, int row, int column)
{
sheet= wb.getSheetAt(sheetnumber);
String data = sheet.getRow(row).getCell(column).getStringCellValue();
return data;
}
public int getRowCount(int sheetIndex)
{
int row = wb.getSheetAt(sheetIndex).getLastRowNum();
row = row + 1;
return row;
}
}
`
Error Screenshot:
Excel File:
You are declaring Object[][] credentials = new Object[rows][2]; but you fill only one column keeping other column empty (null). Hence the dimension of your array does not match the number of arguments your method accepts.
Fix it with changing that line to:
Object[][] credentials = new Object[rows][1];

Cannot get a STRING value from a NUMERIC cell?

I Was Executing Test Scripts Though Excel Sheet Using Keyword Driven Data Framework.
While Executing Am Geting Error as :
java.lang.RuntimeException: java.lang.IllegalStateException: Cannot
get a STRING value from a NUMERIC cell
My Selenium Code is
package DemoData;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import DataConfig.ExcelDataConfig;
public class ReadArrayData
{
WebDriver driver;
#Test(dataProvider="Tipreports")
public void Dataprovider(String username, String password) throws InterruptedException
{
System.setProperty("webdriver.chrome.driver", "F:\\New folder\\chromedriver.exe");
driver = new ChromeDriver();
driver.get("http://xxxxxxxxxxxxxxxx/");
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.findElement(By.id("txt_username")).sendKeys(username);
driver.findElement(By.id("txt_pin")).sendKeys(password);
driver.findElement(By.xpath("//*[#id='btn_click']")).click();
Thread.sleep(5000);
//driver.getCurrentUrl();
Assert.assertTrue(driver.getCurrentUrl().contains("http://xxxxxxxxxxxxx/Algorithm_Run.aspx"),"User Not able to Login - Invalid Credentials");
}
#AfterMethod
public void Close()
{
driver.quit();
}
#DataProvider(name="Tipreports")
public Object[][] passdata()
{
ExcelDataConfig config = new ExcelDataConfig("E:\\Workspace\\KeywordFramework\\TestData\\Dataprovider.xlsx");
int rows = config.getRowCount(0);
Object[][] data = new Object[rows][2];
for(int i=0;i<rows;i++)
{
data[i][0]=config.getData(0, i, 0);
data[i][1]=config.getData(0, i, 1);
}
return data;
}
}
Here is My Excel Data Config Code :
package DataConfig;
import java.io.File;
import java.io.FileInputStream;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelDataConfig
{
XSSFWorkbook wb;
XSSFSheet Sheet1;
public ExcelDataConfig(String excelpath)
{
try
{
File src = new File(excelpath);
FileInputStream fis = new FileInputStream(src);
wb= new XSSFWorkbook(fis);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
public String getData(int sheetnumber, int row, int column)
{
Sheet1 = wb.getSheetAt(sheetnumber);
String data =Sheet1.getRow(row).getCell(column).getStringCellValue();
return data;
}
public int getRowCount(int sheetindex)
{
int row = wb.getSheetAt(sheetindex).getLastRowNum();
row = row+1;
return row;
}
}
Can you please help me to sort out this, Why am getting this error? I have declared 2 Columns and 4 Rows using for loop. But am getting cannot Get The error as cannot get the string value from Numeic Cell.
Try this:
String data;
if(cell.getCellType()==CellType.STRING)
data = cell.getStringCellValue();
else if(cell.getCellType()==CellType.NUMERIC)
data = String.valueOf(cell.getNumericCellValue());
else ...
It is a better way to retrieve the cell content as text.
Thanks to #AxelRichter, the manual show a more complete example to retrieve cell content: https://poi.apache.org/components/spreadsheet/quick-guide.html#CellContents
//try this:
DataFormatter objDefaultFormat = new DataFormatter();
FormulaEvaluator formulaEvaluator = workbook.getCreationHelper().createFormulaEvaluator();
String cellValueStr = objDefaultFormat.formatCellValue( cell , formulaEvaluator );
DataFormatter contains methods for formatting the value stored in an Cell. This can be useful when you need to get data exactly as it appears in Excel.
Supported formats include currency, SSN, percentages, decimals, dates, phone numbers, zip codes, etc.
Thanks to #AxelRichter:
DataFormatter formatter = new DataFormatter();
String text = formatter.formatCellValue(cell);

parse excel data and store as per Map<String, List<>> structure

I have an excel sheet as shown below
Date Amount Client
13/03/2018 79 0017F00000Ujs3C
13/03/2018 86 0017F00000Ujs3C
13/03/2018 50 0017F00000Ujs3C
I need to parse the excel file using apache POI and store data column wise
and store data as per this Map> structure
This is program
import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelReader
{
public static void main(String args[])
{
try
{
File myFile = new File("C:\\Users\\xxx\\Desktop\\test.xlsx");
FileInputStream fis = new FileInputStream(myFile);
Map<String, List<String>> myMaps = new HashMap<String, List<String>>();
XSSFWorkbook workBook = new XSSFWorkbook(fis);
int numberofsheetspresent = workBook.getNumberOfSheets();
DataFormatter dataFormatter = new DataFormatter();
for (int i = 0; i < numberofsheetspresent; i++) {
String sheetname = workBook.getSheetName(i);
XSSFSheet sheet = workBook.getSheet(sheetname);
for (Row eachRow : sheet) {
//List rowDataList = new LinkedList();
for (Cell cellData : eachRow) {
String cellValue = dataFormatter.formatCellValue(cellData);
System.out.println(cellValue);
}
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
It is reading the data row-wise . could you please help me how to create a
Map> structure with the above excel
String : List
Date : {13/03/2018 , 13/03/2018 , 13/03/2018 }
Amount : {79 , 86, 50}
Client : {0017F00000Ujs3C , 0017F00000Ujs3C, 0017F00000Ujs3C}

How to write data to an existing excel using apache poi

My excel sheet contains 5 row and 2 columns.I want to add one more column in that excel.But when i am using WorkbookFactory,it is showing error.I imported poi-3.8.jar and poi-ooxml-3.5-beta5.jar.It is giving error
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
WorkbookFactory cannot be resolved.Please help me what to do.
try this
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelExample {
public static void main(String[] args) throws IOException {
try {
FileInputStream file = new FileInputStream(new File("C:\\test.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);
Row row = sheet.getRow(0);
row.createCell(3).setCellValue("Value 2");
file.close();
FileOutputStream outFile =new FileOutputStream(new File("C:\\update.xls"));
workbook.write(outFile);
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
See the Apache POI Components and Dependencies page for details. You're missing some of the jars, hence the compile error.
If you want to work with both HSSF (.xls) and XSSF (.xlsx), which I guess you do as you're talking about WorkbookFactory, you'll need to include both the main POI jar and the POI-OOXML jar, plus all of their dependencies. With those jars on your classpath, you'll be sorted
Also, you might want to think about using something like Apache Maven or Apache Ivy to handle your dependencies for you, that way you can avoid missing jar problems like this
Are you using Maven?
In case yes, then please refer to the last comment at the following link:
http://apache-poi.1045710.n5.nabble.com/Where-is-WorkbookFactory-td2307412.html
I'm Uploading my program for your reference. After some effort I've overcome this issue.
Jars details: dom4j-1.6.1.jar, poi-3.9.jar,poi-ooxml-3.9.jar, poi-ooxml-schemas-3.11.jar, xmlbeans-2.6.0.jar
Make sure you have at least above mentioned or new. I'm including details of import so that you don't need to bang you head. Hope you find it use
***Pojo: Employee.java***
public class Employee {
private int id;
private String firstName;
private String lastName;
public Employee(){}
public Employee(int id, String firstName, String lastName) {
super();
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
***Write Class: ApachePOIExcelWrite.java***
import java.io.File;
import java.io.FileOutputStream;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ApachePOIExcelWrite {
public static void main(String[] args)
{
//Blank workbook
XSSFWorkbook workbook = new XSSFWorkbook();
//Create a blank sheet
XSSFSheet sheet = workbook.createSheet("Employee Data");
//This data needs to be written (Object[])
Map<String, Object[]> data = new TreeMap<String, Object[]>();
data.put("1", new Object[] {"ID", "NAME", "LASTNAME"});
data.put("2", new Object[] {1, "Amit", "Shukla"});
data.put("3", new Object[] {2, "Lokesh", "Gupta"});
data.put("4", new Object[] {3, "John", "Adwards"});
data.put("5", new Object[] {4, "Brian", "Schultz"});
//Iterate over data and write to sheet
Set<String> keyset = data.keySet();
int rownum = 0;
for (String key : keyset)
{
Row row = sheet.createRow(rownum++);
Object [] objArr = data.get(key);
int cellnum = 0;
for (Object obj : objArr)
{
Cell cell = row.createCell(cellnum++);
if(obj instanceof String)
cell.setCellValue((String)obj);
else if(obj instanceof Integer)
cell.setCellValue((Integer)obj);
}
}
try
{
//Write the workbook in file system
FileOutputStream out = new FileOutputStream(new File("/home/ohelig/eclipse/New Microsoft Office Excel Worksheet.xlsx"));
workbook.write(out);
out.close();
System.out.println("Write Successfully.");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
***Update Class: UpdateExcel.java***
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class UpdateExcel {
public static void main(String[] args) {
XSSFWorkbook workbook=null;
XSSFSheet sheet;
try{
FileInputStream file = new FileInputStream(new File("/home/ohelig/eclipse/New Excel Worksheet.xlsx"));
//Create Workbook instance holding reference to .xlsx file
workbook = new XSSFWorkbook(file);
//Get first/desired sheet from the workbook
//Most of people make mistake by making new sheet by looking in tutorial
sheet = workbook.getSheetAt(workbook.getActiveSheetIndex());
Employee ess = new Employee(6,"Yanish","Pradhananga");
//Get the count in sheet
int rowCount = sheet.getLastRowNum()+1;
Row empRow = sheet.createRow(rowCount);
System.out.println();
Cell c1 = empRow.createCell(0);
c1.setCellValue(ess.getId());
Cell c2 = empRow.createCell(1);
c2.setCellValue(ess.getFirstName());
Cell c3 = empRow.createCell(2);
c3.setCellValue(ess.getLastName());
}
catch (Exception e)
{
e.printStackTrace();
}
try
{
//Write the workbook in file system
FileOutputStream out = new FileOutputStream(new
File("/home/ohelig/eclipse/New Excel Worksheet.xlsx"));
workbook.write(out);
out.close();
System.out.println("Update Successfully");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}

Categories