Selenium reading data from Excel file - java

I am trying to read some test data from an Excel file (3 rows and 2 columns with no blank row in between) but in the output I am getting just the first row of the Excel. After that it is giving me a null pointer exception.
public class ReadDataFromExcel {
public void readExcel(String filePath,String fileName,String sheetName) throws IOException {
File file = new File(filePath+"\\"+fileName);
FileInputStream inputStream = new FileInputStream(file);
Workbook myWorkbook = null;
String fileExtensionName = fileName.substring(fileName.indexOf("."));
if(fileExtensionName.equals(".xlsx")) {
myWorkbook = new XSSFWorkbook(inputStream);
}
else if(fileExtensionName.equals(".xls")) {
myWorkbook = new HSSFWorkbook(inputStream);
}
Sheet mySheet = myWorkbook.getSheet(sheetName);
int rowCount = mySheet.getLastRowNum()- guru99Sheet.getFirstRowNum();
System.out.println("Total rows= " +rowCount);
for (int i = 0; i < rowCount+1; i++) {
Row row = mySheet.getRow(i);
int columnCount = row.getLastCellNum() - row.getFirstCellNum();
for(int j=0; j <= columnCount; j++) {
System.out.print(row.getCell(j).getStringCellValue()+"|| ");
}
System.out.println();
}
}
public static void main(String...strings) throws IOException {
ReadDataFromExcel objExcelFile = new ReadDataFromExcel();
String filePath = System.getProperty("user.dir")+"\\src\\testFileInputOutput";
objExcelFile.readExcel(filePath,"testExcel.xlsx","testSheet");
}
}
I am getting the exception on this line:
System.out.print(row.getCell(j).getStringCellValue()+"|| ");

To get past NullPointerException you can check for null by replacing the line that is throwing the exception with this:
Cell cell = row.getCell(j);
if (cell != null) {
System.out.print(cell.getStringCellValue());
}
System.out.print("|| ");

Related

Testng:Dataprovider: error : sun.reflect.NativeMethodAccessorImpl#2f1ea80d

I am trying to read data from excel which contains only one column with three rows in it
ID
A1002
B1003
C1004
I am using dataprovider in Testng to achieve the same. But on returning the 2D Object array, I am getting sun.reflect.NativeMethodAccessorImpl#2f1ea80d error
#DataProvider(name = "getLoginData")
public Object[][] LoginData() throws Exception
{
Workbook workbook = null;
ArrayList<String> values = new ArrayList<String>();
FileInputStream ExcelFile = new FileInputStream(Path_TestData);
ExcelWBook = new XSSFWorkbook(ExcelFile);
ExcelWSheet = ExcelWBook.getSheet(Home.sheetname);
int rows = ExcelWSheet.getPhysicalNumberOfRows();
System.out.println("Rows is" +rows);
for(int i=1; i<rows; i++)
{
XSSFRow row = ExcelWSheet.getRow(i);
values.add(row.getCell(0).getStringCellValue());
}
System.out.println("value size is" +values.size());
Object[][] returnValue = new Object[10][10];
for(i=0; i<values.size();i++)
{
returnValue[i][0] = values.get(i);
}
return returnValue;
}
#Test(dataProvider="getLoginData")
public void LoginData(String ID)
{
driver.findElement(By.xpath("//*[text()='select']")).click();
//clicking on the ID selected in dropdown
driver.findElement(By.xpath("//*[text()=ID]")).click();
}
Try following code, I've made few adjustments here and there:
#DataProvider(name = "getLoginData")
public static Object[][] LoginData() throws Exception
{
XSSFWorkbook ExcelWBook = null;
ArrayList<String> values = new ArrayList<String>();
FileInputStream ExcelFile = new FileInputStream("C:\\Users\\kushal8\\Desktop\\K1.xlsx");
ExcelWBook = new XSSFWorkbook(ExcelFile);
XSSFSheet ExcelWSheet = ExcelWBook.getSheet("Sheet1");
int rows = ExcelWSheet.getPhysicalNumberOfRows();
System.out.println("Rows is" +rows);
for(int i=1; i<rows; i++)
{
XSSFRow row = ExcelWSheet.getRow(i);
values.add(row.getCell(0).getStringCellValue());
}
System.out.println("value size is" +values.size());
Object[][] returnValue = new Object[15][15];
for(int i=0; i<values.size();i++)
{
returnValue[i][0] = values.get(i);
//System.out.println(returnValue[i][0]);
}
return returnValue;
}

Create groupRows with SXSSFWorkbook

Reading https://poi.apache.org/apidocs/org/apache/poi/xssf/streaming/SXSSFSheet.html#groupRow(int,%20int)
it says that groups should be created inside window size, but how to create groups that overpass window size
This minimal example generates a groupRow from row 2 to row 554 in a excel of 1000 rows with a window size of 200
public static final int ROWS=1000;
public static final int WINDOW_SIZE=100;
//public static final int WINDOW_SIZE=1000;
public static void main(String args[]) throws FileNotFoundException, IOException{
File outputFile = new File("testFile-actual.xlsx");
SXSSFWorkbook sworkbook = new SXSSFWorkbook(WINDOW_SIZE);
creatXLSX(outputFile, sworkbook);
File expectedoutputFile = new File("testFile-expected.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook();
creatXLSX(expectedoutputFile, workbook);
}
private static void creatXLSX(File outputFile, Workbook workbook)
throws IOException, FileNotFoundException {
Sheet sheet = workbook.createSheet();
int posFirstRow = 1;
boolean addgroup = true;
for(int i = 0; i < ROWS; i++) {
Row row = sheet.createRow(i);
Cell cell = row.createCell(0);
cell.setCellValue(i);
if (addgroup && i % WINDOW_SIZE == 0) {
sheet.groupRow(posFirstRow, i);
posFirstRow = i+1;
}
if (i == 556) {
sheet.groupRow(posFirstRow, 553);
posFirstRow = 556;
addgroup = false;
}
}
workbook.write(new FileOutputStream(outputFile));
}
Key is that:
groupRow(1,n)
groupRow(n+1, m)
joins two groups and generate same as
groupRow(1,m)
more info here https://bz.apache.org/bugzilla/show_bug.cgi?id=58077

poi java code to merge cells based on common data

I have data in the above format in an excel file , I want to edit it as follows:
I have used the following code :
public void editExcelTemplate() throws FileNotFoundException, IOException
{
InputStream ExcelFileToRead = new FileInputStream("file.xls");
XSSFWorkbook wb = new XSSFWorkbook(ExcelFileToRead);
XSSFSheet sheet = wb.getSheetAt(0);
int rows = sheet.getPhysicalNumberOfRows();
String cmp = "none";
for(int i=0;i<rows;i++)
{
Row row = sheet.getRow(i);
int col =row.getPhysicalNumberOfCells();
int colIndex = 1;
int v=0;
for(int j=0;j<col;j++)
{
String content = row.getCell(j).getStringCellValue();
if(!(content == cmp) && !(content.equals("none")))
{
if(!(cmp.equals("none")))
{
System.out.println("content: "+content);
System.out.println("cmp: "+cmp);
v= j;
System.out.println("row : "+i+"colst : "+(colIndex)+"colend : "+v);
if(!( v-colIndex == 0) && v>0)
{
System.out.println("row : "+i+"colst : "+(colIndex)+"colend : "+v);
sheet.addMergedRegion(new CellRangeAddress(i,i,colIndex-1,v-1));
System.out.println("merged");
}
}
}
if(!(content == cmp))
{
colIndex = v+1;
}
cmp = content;
}
}
FileOutputStream excelOutputStream = new FileOutputStream(
"file.xls");
wb.write(excelOutputStream);
excelOutputStream.close();
}
I endedup getting the following output :
Can anybody help me get an appropriate output ? The main purpose is to merge the cells with common data in the entire proces.

cannot get a numerical value from the excel cell

public Object[][] dataProviderMethod() throws IOException {
try {
file = new FileInputStream(new File("/Users/nanthakumar/Documents/workspace/Myna_Admin/src/com/myna/testdata/login.xls"));
workbook = new HSSFWorkbook(file);
sheet = workbook.getSheetAt(0);
row = sheet.getLastRowNum() + 1;
col = sheet.getRow(0).getLastCellNum();
data = new String[row][col];
for (i = 0; i < row; i++) {
rowvalue = sheet.getRow(i);
for (j = 0; j < col; j++) {
cellValue = rowvalue.getCell(j);
data[i][j] = cellValue.getStringCellValue();
System.out.println("The value is ----->" + data[i][j]);
}
workbook.close();
file.close();
}
} catch (FileNotFoundException nana) {
nana.printStackTrace();
}
return data;
}
This is my code and I tried to add the getnumericalCellvalue() instead of getStringCellValue() but that is not working for me.
first you have to check in the template excel whether the column is number or text.you can get the numerical value if and only if the column is of type number.so change the template excel and try

Apache POI append data to excel sheet not working

I am reading data from an arraylist and writing this to an excel sheet. The problem is my excel is getting overwritten each time. Here is my code. I can't figure out what is wrong here :( Can someone please help?
public static void main( String[] args ) throws Exception
{
List<String> fileData = new ArrayList<String>();
for(File file:files) {
fileData.add(readFileContents(file.getAbsolutePath()));
}
for(String fileContent:fileData) {
//do some stuff that in turn calls the writeDataToExcel method
}
}
private static void writeDataToExcel(String test,Map<String,String> dataMap,Object object) throws IOException {
File file = new File("input/data.xls");
Map<String,Object[]> data = new LinkedHashMap<String,Object[]>();
XSSFWorkbook workbook = null;
int count = 0;
XSSFSheet sheet = null;
if(file.exists()) {
workbook = new XSSFWorkbook(new FileInputStream(file));
sheet = workbook.getSheet("Data Sheet");
}
else {
workbook = new XSSFWorkbook();
sheet = workbook.createSheet("Data Sheet");
//count = sheet.getLastRowNum();
}
data.put("1", new Object[]{"Id","Name","Field","Description","Value"});
for(Map.Entry<String, String> dataMp:dataMap.entrySet()) {
data.put(Integer.toString(count+2), new Object[]{id,object.getClass().getSimpleName(),dataMp.getKey(),dataMp.getValue(),"null"});
count++;
}
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);
}
}
FileOutputStream fis = new FileOutputStream("input/data.xls");
workbook.write(fis);
if(fis!=null)
fis.close();
}
I think problem is at line
int rownum = 0;
this will set rowNUm to zero each time and sheet will be written from zero row
You need to persist this rowNum value if you want to append data in the sheet

Categories