How to get data from xlsx sheet using dataprovider in selenium TestNG? - selenium

Can someone give me the logic of how to retrieve data from an Excel sheet (latest Excel file format) using the data provider in Selenium?
I'm mostly looking for the for loop logic inside the data provider.

Bascially, TestNG Data Provider is anything you create.
If you want to read xlsx files you need to create a class which reads excel rows and returns dataset.
#DataProvider(name = "data")
public static Object[][] returnExcelSheetData()
throws BiffException, IOException
{
String absolutePath = filePath.concat("/").concat(fileName); //path to excel file
FileInputStream file = new FileInputStream(new File(absolutePath));
Workbook workbook = Workbook.getWorkbook(file);
Sheet worksheet = workbook.getSheet(sheetName); //sheet name
int ROWS = worksheet.getRows() - 1; //if headers are present - use -1
int COLS = worksheet.getColumns(); //read all columns
Object[][] dataset = new Object[ROWS][COLS];
for (int rowCount = 0; rowCount < ROWS; rowCount++) {
for (int colCount = 0; colCount < COLS; colCount++) {
dataset[rowCount][colCount] = worksheet.getCell(colCount,
rowCount + 1).getContents();
}
}
workbook.close();
file.close();
return dataset;
for loops interate through ALL columns and ALL rows and return data sets.
If you use only 1 row of data and 1 row of headers, DataProvider will pass data to test.
If you use 2 rows of data, method which invokes DataProvider will be invoked for each row (2 times for 2 rows of data)

Related

can we use common data provider method for various test cases in selenium? Can i pass the excel path and sheet name to common data provider?

I have more than one test case naming as classAtest1, classAtest2,classAtest1 etc
Now i am doing each and every class i have to write data provider method seprately
but i want to write only one data provider method and i can able to use it with all the classes by passing excel, path and sheet name
**#DataProvider(name="getData")** // supplying data for a test method.
public Object[][] getData() throws IOException
{
FileInputStream fis = new FileInputStream("**Z:\\MAANTTIANS\\folder\\Excel Sheets\\QestionBank.xlsx**"); // Your .xlsx file name along with path
excelWorkbook = new XSSFWorkbook(fis);
// Read sheet inside the workbook by its name
excelSheet = excelWorkbook.getSheet("**MTFQuestion**"); //Your sheet name
// Find number of rows in excel file
System.out.println("First Row Number/index:"+ excelSheet.getFirstRowNum() + " *** Last Row Number/index:"+ excelSheet.getLastRowNum());
int rowCount = excelSheet.getLastRowNum() - excelSheet.getFirstRowNum()+1;
int colCount = excelSheet.getRow(0).getLastCellNum();
System.out.println("Row Count is: " + rowCount+ " *** Column count is: " + colCount);
Object data[][] = new Object[rowCount-1][colCount];
for (int rNum = 2; rNum <= rowCount; rNum++)
{
for (int cNum = 0; cNum < colCount; cNum++)
{
data[rNum - 2][cNum] = getCellData("MTFQuestion", cNum, rNum); //Your sheet name
}
System.out.println();
}
return data;
}
}
Yes we can use.
You can pass DataProvider name to each #Test method, TestNG will execute each test case with alphabetic order.

EPPlus - How to set data type of a column to General

In my ASP.NET Core 1.1 app I'm using EPPlus.Core to export data to Excel. Some columns exported have mostly numbers but rarely a text (e.g. N/A). These columns in generated Excel are showing (as expected) a green triangle on the top left corner of their cells. I want to get rid of those warnings.
Question: What's a good way of getting rid of those triangles when Excel is generated? I tried setting the format of these columns to text as follows but it did not work. I guess we need to set the format of these columns to General but I can't figure out how:
workSheet.Cells["D1:P1"].Style.Numberformat.Format = "General";
UPDATE:
Per a user's request, the code looks similar to following.
Error at inner loop for (var j = 4; j < testlist[i].Count(); j++){...}: MyViewModel does not contain a definition of Count()
Error at line if (testlist[i][j] is string){...}: cannot apply indexing with [] to an extension of type MyViewModel
Controller:
....
....
var testlist = (qry to load a MyViewModel).ToList();
using (ExcelPackage pkg= new ExcelPackage())
{
var ws = excel.Workbook.Worksheets.Add("TestWorkSheet");
ws.Cells[1, 1].LoadFromCollection(rc_excel, true);
//I'm starting from 2nd row and 5th column
for (var i = 1; i < testlist.Count; i++)
{
for (var j = 4; j < testlist[i].Count(); j++)
{
if (testlist[i][j] is string)
{
....
....
}
}
pkg.Save();
return(....);
}

How to save Excel Table as a Picture using vb.net?

I'm trying to save tables from excel sheets as pictures. Is there a way to just put that table on the clipboard and save it? This is what I've got so far but the library referenced is not there?
Thank you in advance!
-Rueben Ramirez
Public Sub extract_excelTable(ByRef data_file As String, ByRef app1 As excel.Application, ByRef sheet_name As String)
'defining new app to prevent out of scope open applications
Dim temp_app As excel.Application = app1
Dim workbook As excel.Workbook = temp_app.Workbooks.Open(Path.GetFullPath(data_file))
temp_app.Visible = False
For Each temp_table As excel.DataTable In workbook.Worksheets(sheet_name)
temp_table.Select()
'temp_app.Selection.CopyAsPicture?
Next
End Sub
I'm not going to write any code here, but I will outline a solution for you that will work. Note that this will not reproduce the formatting of the excel document, just simply get the data from it, and put it on an image in the same column/row order as the excel file.
STEP 1:
My solution to this problem would be to read the data from the excel file using an OLEDB connection as outlined in the second example of this post: Reading values from an Excel File
Alternatively, you may need to open the document in excel and re-save it as a CSV if it's too large to fit in your computer's memory. I have some code that reads a CSV into a string list in C# that may help you:
static void Main(string[] args)
{
string Path = "C:/File.csv";
System.IO.StreamReader reader = new System.IO.StreamReader(Path);
//Ignore the header line
reader.ReadLine();
string[] vals;
while (!reader.EndOfStream)
{
ReadText = reader.ReadLine();
vals = SplitLine(ReadText);
//Do some work here
}
}
private static string[] SplitLine(string Line)
{
string[] vals = new string[42];
string Temp = Line;
for (int i = 0; i < 42; i++)
{
if (Temp.Contains(","))
{
if (Temp.Substring(0, Temp.IndexOf(",")).Contains("\""))
{
vals[i] = Temp.Substring(1, Temp.IndexOf("\",", 1) - 1);
Temp = Temp.Substring(Temp.IndexOf("\",", 1) + 2);
}
else {
vals[i] = Temp.Substring(0, Temp.IndexOf(","));
Temp = Temp.Substring(Temp.IndexOf(",") + 1);
}
}
else
{
vals[i] = Temp.Trim();
}
}
return vals;
}
STEP 2:
Create a bitmap object to create an image, then use a for loop to draw all of the data from the excel document onto the image. This post had an example of using the drawstring method to do so: how do i add text to image in c# or vb.net

How to send specific rows of excel to data provider in testNG?

I have created an excel containing multiple rows, each row corresponding to a test case. The Excel has around 22 columns (parameters) including a "Flag" column.
I want the Dataprovider to return only those columns which has a value 'Y' in the excel column. The use case is that when the client wants to run a particular test case, they only need to flag it to Y or N. How can I achieve this is in TestNG with Selenium?
My colleague had helped me to achieve this using following code, but this does not work as per my new code structure.
#DataProvider(name = "Order")
public Object[][] menu()
{
Object[][] data = UtilLibrary.getData("Order");
int intColCount = UtilLibrary.datatable.getColumnCount("Order");
int j = 0;
int arrRowCount=0;
for (int i = 0; i < data.length; i++) {
if((data[i][intColCount-1]).equals("Y"))
{
arrRowCount++;
}
}
j=0;
Object[][] retData = new Object[arrRowCount][intColCount];
for (int i = 0; i < data.length; i++)
{
if ((data[i][intColCount-1]).equals("Y")) {
retData[j] = data[i]; j++; }
}
return retData;
}
The above code sends only the record/s having flag='Y' in the excel to the Dataprovider. But, it was working only when the test script had a single #Test method having all automation steps, while now I have multiple #Test methods to simulate the same steps to which I have passed this same Dataprovider (Order).
Let me know if someone has achieved this using a similar code or if TestNG has a specific feature to send filtered rows of excel to the Dataprovider
I have now fixed the issue. The reason why the above given code for rows having flag = 'Y' in Excel was not working with multiple #Test methods was only due to a silly mistake. The mistake was that I had changed the excel structure a bit and did not modify the above code as per the index of the new flag column.

creating multiple pdfs from multiple excel files that support both formats in java

below is my code to convert excel to pdf, but i dont understand how do i generate multiple pdf from multiple excel sheets.
String files;
File folder = new File(dirpath);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
files = listOfFiles[i].getName();
if (files.endsWith(".xls") || files.endsWith(".xlsx")) {
// inputting files one by one
//here it should take an input one by one
System.out.println(files);
String inputR = files.toString();
FileInputStream input_document = new FileInputStream(new File("D:\\ExcelToPdfProject\\"+inputR));
// Read workbook into HSSFWorkbook
Workbook workbook = null;
if (inputR.endsWith(".xlsx")) {
workbook = new XSSFWorkbook(input_document);
System.out.println("1");
} else if (inputR.endsWith(".xls")) {
workbook = new HSSFWorkbook(input_document);
System.out.println("GO TO HELL ######");
} else {
System.out.println("GO TO HELL");
}
Sheet my_worksheet = workbook.getSheetAt(2);
// Read worksheet into HSSFSheet
// To iterate over the rows
Iterator<Row> rowIterator = my_worksheet.iterator();
//Iterator<Row> rowIterator1 = my_worksheet.iterator();
//We will create output PDF document objects at this point
Document iText_xls_2_pdf = new Document();
PdfWriter writer = PdfWriter.getInstance(iText_xls_2_pdf, new FileOutputStream("D:\\Output.pdf"));
iText_xls_2_pdf.open();
//we have two columns in the Excel sheet, so we create a PDF table with two columns
//Note: There are ways to make this dynamic in nature, if you want to.
Row row = rowIterator.next();
row.setHeight((short) 2);
int count = row.getPhysicalNumberOfCells();
PdfPTable my_table = new PdfPTable(count);
float[] columnWidths = new float[count];
my_table.setWidthPercentage(100f);
//We will use the object below to dynamically add new data to the table
PdfPCell table_cell;
I want something that can help me create a folder full of pdfs.