Reading Data from Excel Sheet in Selenium WebDriver - excel

I am Using Selenium WebDriver and reading Data from a excel sheet that contains
Username and Password but the problem is this sheet contains both numeric Values and String Values due to which its throwing error:
Cannot get a STRING value from a NUMERIC cell
Username: rainrrr , shamz, tabraiz
Password: rainrrr ,123456,123456
Please Help
public void AdminLogin(String UserName, String Password) throws Exception
{
System.setProperty("webdriver.chrome.driver", "C:\\Users\\amomin\\Desktop\\selinium\\chromedriver.exe");
driver =new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("My Path");
driver.findElement(By.xpath(".//*[#id='UserName']")).sendKeys(UserName);
driver.findElement(By.xpath(".//*[#id='Password']")).sendKeys(Password);
driver.findElement(By.xpath(".//*[text()='Submit']")).click();
Thread.sleep(5000);
Assert.assertTrue(driver.getTitle().contains("Dashboard - RainMaker"),"Login Fail");
System.out.println("User Login Successfully");
}
public Object[][] LoginData()
{
libDDT config=new libDDT("C:\\Users\\amomin\\workspace\\DataDrivenTest\\TestData\\TestData.xls");
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;
}

Try this by saving Numeric values in text format.
If the string is starting with number, in excel, format data as text by prefixing numeric value with single quotation ('). Ex: 123 as '123

Related

Read excel content after get data from particular cell

I have existing codes that work to get a particular cell from an excel sheet.
is that possible to read particular content within the cell?
excel reader:
public String ReadCellData(int vRow, int vColumn)
{
String value=null; //variable for storing the cell value
Workbook wb=null; //initialize Workbook null
try
{
//reading data from a file in the form of bytes
FileInputStream fis=new FileInputStream(RunConfiguration.getProjectDir() + "/Data Files/testmatrix.xlsx");
//constructs an XSSFWorkbook object, by buffering the whole stream into the memory
wb=new XSSFWorkbook(fis);
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
catch(IOException e1)
{
e1.printStackTrace();
}
Sheet sheet=wb.getSheetAt(0); //getting the XSSFSheet object at given index
Row row=sheet.getRow(vRow); //returns the logical row
Cell cell=row.getCell(vColumn); //getting the cell representing the given column
//value=cell.getStringCellValue(); //getting cell value
//return value; //returns the cell value
}
}
codes to get and print data
//read excel cell C11, ignore first row column A1. (int vRow, int vColumn)
def exceldata = CustomKeywords.'test.readexcel.ReadCellData'(11, 2)
String jsondata = JsonOutput.prettyPrint(exceldata.toString())
println(jsondata)
WebUI.delay(1)
//call the object and post the above data as API HTTP request body
def post = ((findTestObject('Object Repository/Web Service Request/test-service/Post')) as RequestObject)
post.setBodyContent(new HttpTextBodyContent(jsondata))
WebUI.delay(2)
//POST and verification
def response = WS.sendRequestAndVerify(post)
println(response.statusCode)
assert response.getStatusCode() == 201
excel data at Cell C11
I want to get the value of key testId.
{
"testId": "test123",
"created": "2020-02-06T17:02:39.257Z",
}
You will need to parse the response:
def parsedResponse = new JsonSlurper().parseText(response.getResponseText())
println parsedResponse.get("testId")
(don't forget to import groovy.json.JsonSlurper)

PX.Data.XLSXReader not reading first row

I'm using the XLSXReader to read an Excel file, but it is failing to read the first row. I need to read the first row since it contains data and not headers.
Using test data, I put in a blank first row, but it still skipped the first row with data:
I copied the first row and duplicated it and it read the row:
I don't know why it is automatically skipping the first row.
Here is the action button code that imports the file, saves it, and reads it:
public PXAction<PMProject> importCostBudget;
[PXButton(CommitChanges = true)]
[PXUIField(DisplayName = "Import Cost Budget")]
protected void ImportCostBudget()
{
if (ImportCostBudgetView.AskExt() == WebDialogResult.OK)
{
const string PanelSessionKey = "ImportCostBudget";
PX.SM.FileInfo info = (PX.SM.FileInfo)PX.Common.PXContext.SessionTyped<PXSessionStatePXData>().FileInfo[PanelSessionKey];
Byte[] bytes = info.BinData;
System.Web.HttpContext.Current.Session.Remove(PanelSessionKey);
if (info != null)
{
PXNoteAttribute.AttachFile(Base.Project.Cache, Base.Project.Current, info);
using (PX.Data.XLSXReader reader = new XLSXReader(bytes))
{
//List<PMCostBudget> costBudgets = new List<PMCostBudget>();
reader.Reset();
//This is to read the first row
RowRead(reader);
while (reader.MoveNext())
{
RowRead(reader);
}
}
}
}
}
Is there a way I can force read the very first row using the reader?
Header row is likely treated as a special case intended for reading column names.
You should be able to access it from the XLSXReader IndexKeyPairs collection:
public IDictionary<int, string> IndexKeyPairs
{
get { return _header; }
}

Excel download using Angular and Spring Boot produces corrupt xls file

Iam trying to write a xls download for my Spring boot application. In order to generate the file Iam using POI. If I download the file directly from my Controller without passing it to the front-end like so:
//Wrote this one just for testing if the file is already corrupt here.
FileOutputStream fos = new FileOutputStream("C:\\dev\\directDownload.xls");
fos.write(byteArray);
fos.flush();
fos.close();
}
It works just fine and the file looks like this:
xls when downloaded from the backend without passing it to angular:
However thats not my goal. I intend to pass the Outputstream to my angular component. The Component calls a function from a service class. This class gets the response from the controller and passes it back to my component. In the UI the downloading dialog opens. The problem is, that the downloaded file looks like this (doesnt matter if its opened via excel or open office):
Currupt xls:
My Java Controller:
#CrossOrigin(exposedHeaders = "Content-Disposition")
#RequestMapping(value = "/report/file", produces = "application/vnd.ms-excel;charset=UTF-8")
public void getReportFile(#RequestParam(name = "projectNumber") final String projectNumber,
#RequestParam(name = "month") final int month, #RequestParam(name = "year") final int year,
#RequestParam(name = "employee") final int employee,
#RequestParam(name = "tsKey") final String tsKey,
final HttpServletResponse response) throws IOException {
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
String excelFileName = "test.xls";
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"",
excelFileName);
response.setHeader(headerKey, headerValue);
//Here I create the workbook that I want to download
ProjectMonthReport report = reportService.getReport(projectNumber, month, year);
//ExcelService builts the workbook using POI
Workbook workbook = excelService.exportExcel(report, employee, tsKey);
//The response is stored in an outputstream
OutputStream out = response.getOutputStream();
response.setContentType("application/vnd.ms-excel");
byte[] byteArray = ((HSSFWorkbook)workbook).getBytes();
out.write(byteArray);
out.flush();
out.close();
//Wrote this one just for testing if the file is already corrupt here. --> It's fine.
FileOutputStream fos = new FileOutputStream("C:\\dev\\directDownload.xls");
fos.write(byteArray);
fos.flush();
fos.close();
}
The Java Service method that builds the file using POI:
public Workbook exportExcel(final ProjectMonthReport report, final int employee, final String tsKey) throws IOException,
InvalidFormatException {
Workbook workbook = new HSSFWorkbook();
CreationHelper createHelper = workbook.getCreationHelper();
// Create a Sheet
Sheet sheet = workbook.createSheet("Employee");
// Create a Font for styling header cells
Font headerFont = workbook.createFont();
headerFont.setBold(true);
headerFont.setFontHeightInPoints((short) 14);
headerFont.setColor(IndexedColors.RED.getIndex());
// Create a CellStyle with the font
CellStyle headerCellStyle = workbook.createCellStyle();
headerCellStyle.setFont(headerFont);
Row headeRow = sheet.createRow(0);
Cell dateHeader = headeRow.createCell(0);
dateHeader.setCellValue("Datum");
Cell startHeader = headeRow.createCell(1);
startHeader.setCellValue("Beginn");
Cell endHeader = headeRow.createCell(2);
endHeader.setCellValue("Ende");
Cell activityHeader = headeRow.createCell(3);
activityHeader.setCellValue("Tätigkeitsbereit");
Cell cardHeader = headeRow.createCell(4);
cardHeader.setCellValue("Kartennummer");
List<WorkDescriptionDetail> details = report.getEmployees().get(employee).getKeyDetailMap().get(Integer.valueOf(tsKey)).getDetailList();
int counter = 1;
for (WorkDescriptionDetail detail : details) {
List <String> stringList= detail.toStringList();
Row row = sheet.createRow(counter);
Cell cellDate = row.createCell(0);
cellDate.setCellValue(stringList.get(0));
Cell cellStart = row.createCell(1);
cellStart.setCellValue(stringList.get(1));
Cell cellEnd = row.createCell(2);
cellEnd.setCellValue(stringList.get(2));
Cell cellActivity = row.createCell(3);
cellActivity.setCellValue(stringList.get(3));
counter ++;
}
return workbook;
}
My angular component:
saveFile(employee: string, tsKey:string) {
this.subscription = this.reportService.saveXlsFile(this.projectNumber, this.year, this.month, employee, tsKey)
.subscribe(response=> {
console.log(response);
let mediatype = 'application/vnd.ms-excel;charset=UTF-8';
const data = new Blob(["\ufeff",response.arrayBuffer()], {type: mediatype});
console.log(data);
saveAs(data, 'test.xls');
},
error => console.log("error downloading the file"));
}
The Ts Service Function that is called:
saveXlsFile(projectNumber:string, year:string, month:string, empId: string, tsKey:string) {
let params:URLSearchParams = new URLSearchParams();
params.set('projectNumber', projectNumber);
console.log(projectNumber);
params.set('month', month);
console.log(month);
params.set( 'year', year);
console.log(year);
params.set('employee', empId);
console.log(empId);
params.set('tsKey', tsKey);
console.log(tsKey);
return this.http.get(this.baseUrl + "/file", { search: params } );
}
I tried to retrieve the response via Postman and directly download the file. When I do that the file can't be opened by excel (Excel just crashed), however I can open the file in the OpenOffice version and it works fine. Its also not corrupted.
I've been searching the web for the last couple of days and I think it may be an enconding problem caused in the frontend. But maybe it is also SpringBoot thats playing me here. Any suggestions?
Thank you for your help!
Hey I found the solution to this problem yesterday myself. Adding the following in the angular service:
return this.http.get(this.baseUrl + "/file", { search: params, responseType: ResponseContentType.Blob }).map(
(res) => {
return new Blob([res.blob()], { type: 'application/vnd.ms-excel' });
});
After that you'll need to modify the component like so:
saveFile(employee: string, tsKey:string) {
this.subscription = this.reportService.saveXlsFile(this.projectNumber, this.year, this.month, employee, tsKey)
.subscribe(response=> {
console.log(response);
let mediatype = 'application/vnd.ms-excel';
saveAs(response, 'test.xlsx');
},
error => console.log("error downloading the file"));
}
So the Problem was that I was not getting a blob Object in my response....

csv save data only in one cell instead of a row

I have the following code which writes data to the CSV file.
But instead of writing the headers each in different cell it writes all in the same cell.
When i change to "UTF-8" it works fine but writs "Gibberish" instead of correct letters when opened in Office Excel.
CSVWriter csvWrite = new CSVWriter(new OutputStreamWriter(new FileOutputStream(file),
"UTF-16"), CSVWriter.DEFAULT_SEPARATOR ,CSVWriter.NO_QUOTE_CHARACTER,
CSVWriter.DEFAULT_ESCAPE_CHARACTER, CSVWriter.DEFAULT_LINE_END);
//Add Columns headers to the excel file
String columnHeaders[] = {"אאא","בבב","גגג"};
csvWrite.writeNext(columnHeaders);
//Collect Data
ArrayList<String[]> listData = collectDataFromDBToList();
//Write/Add all line from list to the csv file
csvWrite.writeAll(listData);
csvWrite.close();
Received output
Wanted output
Thank phoenix but it did not helped.
I found the solution :) , it was just to use tab separator instead of the default one.
use: '\t' instead of CSVWriter.DEFAULT_SEPARATOR
CSVWriter csvWrite = new CSVWriter(new OutputStreamWriter(new FileOutputStream(file),
"UTF-16"),'\t' ,CSVWriter.NO_QUOTE_CHARACTER,
CSVWriter.DEFAULT_ESCAPE_CHARACTER, CSVWriter.DEFAULT_LINE_END);
Here is this code that i wrote for a project..the values outside for loop ( "WSDL Name" and "Tags" are the column header and list will contain values to be inserted). It will generate test.csv
import java.io.FileWriter;
import java.io.IOException;
public class genCSV
{
public static void main(String [] args)
{
generateCsvFile("c:\\test.csv");
}
private static void generateCsvFile(String sFileName)
{
try
{
FileWriter writer = new FileWriter(sFileName);
writer.append("WSDLName");
writer.append("Tags");
writer.append('\n');
for(int i=0;i<list.size();i++){
writer.append(list.getKey);
writer.append(list.getValueForKey);
writer.append('\n');
}
//generate whatever data you want
writer.flush();
writer.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}

adding an image component to Table cell by overidding `createCell`

I am using LWUIT and showing data with Table, say, flight information!
Instead of writing air companies with text I just like to replace them with icons.
So, I need to override protected Component createCell(Object value, final int row, final int column, boolean editable) method of Table.
This is how I've implemented:
Initializing
imgAln[i]=null;
try {
imgAln[i] = Image.createImage(strPathToImage[i]);
//e.g /uta.png,/somonair.png and so on
lAln[i] = new Label(imgAln[i]);
} catch (IOException e) { }
Creating Table object
Table table = new Table(model) {
protected Component createCell(Object value, final int row,
final int column, boolean editable) {
final Component c = super.createCell(value, row, column, editable);
if (column == 6) {
return lAln[value]; //it does not work here
}
}
};
need help to add Image to table cell!!!
Is there any example??? links are welcome!
The problem in your createCell(...) implementation is that it does not return the super.createCell(...) when the column is not 6. Also your array of labels (lAln) may not be properly created. Try my implementation below, but make sure you store the appropriate image name in the table models' column 0.
This should solve it:
TableModel model = new DefaultTableModel(
new String[]{"Uneditable", "Editable", "CheckBox", "Multiline"},
new Object[][]{
{"/animations.png", "", new Boolean(false), "Multi-line text\nright here"},
{"/buttons.png", "", new Boolean(true), "Further text that\nspans lines"},
{"/dialogs.png", "", new Boolean(true), "No span"},
{"/fonts.png", "", new Boolean(false), "Spanning\nFor\nEvery\nWord"},
});
Table table = new Table(model) {
protected Component createCell(Object value, final int row,
final int column, boolean editable) {
if (row != -1 && column == 0) {
try {
//In my case Column 0 store the resource path names
return new Label(Image.createImage((String)value));
} catch (Exception ex) {
ex.printStackTrace();
}
}
return super.createCell(value, row, column, editable);
}
};
NOTE: If you see the names instead of images in column 0 it means the image path is incorrect, fix it to see the images.
Did you manage to have a look at TableLayoutDemo.java in project LWUITDemo? If i remember it correct, this comes bundled download package LWUIT1.5.zip (or you can always google it).
Let me know if you need more specific help.

Resources