Changing null to blank while reading excel using java - java

If I use a excel sheet that has blank values, this code gives an error of "java.lang.NullPointerException". Is there a way to change the null values to blank? Thanks.
public class GradesDB {
public static void main (String[] args) throws Exception {
//initiating workbook
File excel = new File("Users/Database.xlsx"); //file location
FileInputStream fis= new FileInputStream(excel);
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet ws = wb.getSheet("Students"); //sheet with null value
int rowNum = ws.getLastRowNum() +1;
int colNum = ws.getRow(0).getLastCellNum();
String[][] data = new String[rowNum][colNum]; //storing row and col
//iteration
for (int i =0; i <rowNum; i++) {
XSSFRow row = ws.getRow(i);
for (int j = 0; j <colNum; j++){
XSSFCell cell = row.getCell(j);
String value = cellToString(cell);
data[i][j] = value;
System.out.println(value);
}
}
//System.out.println(data[4][3]);
}
public static String cellToString(XSSFCell cell) {
int type;
Object result = null;
type = cell.getCellType();
switch (type) {
case 0 :
result = cell.getNumericCellValue(); //numeric value
break;
case 1 :
result = cell.getStringCellValue(); //string value
break;
case 2 :
result = cell.getBooleanCellValue();
break;
}
return result.toString();
}
}
I am not sure where the problem is.

Related

Data driven framework in eclipse using Baseclass

I am using loop statement but the final result not returned. i am trying static variable but not accept that. please give me any suggestions
public static String getMultipleExcelVlue(String sheetName) throws IOException {
String res = null;
// 1.mention the path
File file = new File("C:\\Users\\Lap662\\eclipse-workspace\\DVT-Creation\\ExcelSheet\\Excel.xlsx");
// 2.read the object
FileInputStream stream = new FileInputStream(file);
// 3.create workbook
Workbook workbook = new XSSFWorkbook(stream);
// 4.get the sheet
Sheet sheet = workbook.getSheet("Sheet1");
int lastRowNum = sheet.getLastRowNum();
// 5.get the row
int lastCellNum = sheet.getRow(1).getLastCellNum();
for (int i = 1; i <= lastRowNum; i++) {
Row row = sheet.getRow(i);
for (int j = 0; j < lastCellNum; j++) {
Cell cell = row.getCell(j);
CellType type = cell.getCellType();
// 8.switch case
switch (type) {
case STRING:
res = cell.getStringCellValue();
break;
case NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
Date dateCellValue = cell.getDateCellValue();
SimpleDateFormat dateformat = new SimpleDateFormat("dd/MM/yyyy");
res = dateformat.format(dateCellValue);
} else {
double d = cell.getNumericCellValue();
long round = Math.round(d);
if (round == d) {
res = String.valueOf(round);
} else {
res = String.valueOf(d);
}
break;
}
default:
break;
}
}
}
return res;
}

POI XSSF reading all columns not just all defined columns - results not expected

Is there a way to not read the entire Excel documents row, I'm reading the cell's defined in the document, but, it's pulling in the entire sheet's columns???
I'm converting an Excel document to a CSV document. I am getting this result.
Aircraft ID (FADEC_SHIP_POS),Fleet (Fleet Name),Fault Date (TIMESTAMP or FADEC_DATE_TIME),Fault ID (FADEC_ID),Fault Description (FADEC_FAULT_DESCRIPTION),Priority (FADEC_PRIORITY),ATA,Flight Phase (FM),Report Type (REPORT_TYPE),Flight Number (FLT),Origin (ORIG),Destination (DEST),Site Reference Name,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
I don't need all those extra undefined columns, (,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,)
also, there can be empty values in the row's defined columns: - these are expected and needed
6808-1,B757,2019-09-25 20:50:18,351-21A,P(S) 351-21,3,,Climb,901,1278,,,Sprint Airlines
my class
public class XlsxToCsv implements Processor {
private Logger log = Logger.getLogger(XlsxToCsv.class.getName());
private static final String CSV_SEPERATOR_CHAR=",";
private static final String NEW_LINE_CHARACTER="\r\n";
#Override
public void process(Exchange exchange) throws Exception {
log.info("Entering XLSX Excel to CSV ...");
int sheetIdx = 0;
byte[] in = exchange.getIn().getBody(byte[].class);
String out = excelToCSV(in,sheetIdx);
exchange.getIn().setBody(out);
log.info("Exiting XLSX Excel to CSV ...");
}
private String excelToCSV(byte[] xlsxFile, int sheetIdx) throws Exception {
InputStream is = null;
StringBuffer sb = new StringBuffer();
String cellVal = "";
try {
is = new ByteArrayInputStream(xlsxFile);
} catch (Exception e) {
e.printStackTrace();
}
XSSFWorkbook workBook = new XSSFWorkbook(is);
XSSFSheet workSheet = workBook.getSheetAt(sheetIdx);
for (int i = 0; i < workSheet.getPhysicalNumberOfRows(); i++) {
XSSFRow row = workSheet.getRow(i);
for (int j = 0; j < row.getPhysicalNumberOfCells(); j++) {
cellVal = getCellValueAsString(workBook, row.getCell(j));
if ( j == row.getPhysicalNumberOfCells() - 1) {
sb.append(cellVal).append(NEW_LINE_CHARACTER);
} else {
sb.append(cellVal).append(CSV_SEPERATOR_CHAR);
}
}
}
workBook.close();
return sb.toString();
}
private String getCellValueAsString(XSSFWorkbook workbook, XSSFCell cell) {
String cellValue = "";
if (cell != null) {
CellType cellType = cell.getCellType();
if (cellType == CellType.FORMULA) {
FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
cellType = evaluator.evaluateFormulaCell(cell);
}
switch (cellType) {
case STRING:
cellValue = cell.getStringCellValue();
break;
case NUMERIC:
Double doubleValue = cell.getNumericCellValue();
int intValue = doubleValue.intValue();
cellValue = Integer.toString(intValue);
break;
case BOOLEAN:
cellValue = Boolean.toString(cell.getBooleanCellValue());
break;
case ERROR:
cellValue = cell.getErrorCellString();
break;
case BLANK:
break;
default:
break;
}
}
return cellValue;
}
}
It turns out that the template I'm using had spaces entered in the last elements in the spreadsheet, I removed and cleaned up the xlsx template and it is working as expected.
always learning, I wouldn't expect that, but, it is what it is,

Apache POI - Reading excel file in 2D array - returning null values

I am trying to read Excel -2*2 matrix through Apache POI. But the first value returned by 2D array is [null,null]. Please check my code and advise for suitable corrections.
public String[][] getDataArray(String sheetName)
{
String value ="";
String[][] data = null;
int rowCount = wb.getSheet(sheetName).getLastRowNum();
int colCount = wb.getSheet(sheetName).getRow(1).getLastCellNum()-1;
data = new String[rowCount][colCount];
for(int i=1; i<=rowCount;i++)
{
Row row = wb.getSheet(sheetName).getRow(i);
for(int j=0;j<colCount;j++)
{
Cell cell = row.getCell(j);
if(cell.getCellType()==Cell.CELL_TYPE_NUMERIC)
{
value = ""+cell.getStringCellValue();
}
else
{
value = cell.getStringCellValue();
}
data[i][j] = value;
}
}
return data;
}
The debug view where we can see that the first value stored in the variable data is null, null
The excel which i am trying to read. I need only the userName and password data(2*2) alone. Not the header and Run mode datas.
Of course the value in the index 0 will be null because the i starts from 1 and not 0
for (int i = 1; i <= rowCount; i++) //i starts from one
...
data[i][j] = value;
either initialize the i from 0 or do like this
data[i-1][j] = value;
public static String[][] getSheetData(final String fileName, final String workSheetName)
throws Exception {
Integer lastRow = null;
short lastCol = 0;
String[][] sheetData = null;
FileInputStream file=new FileInputStream(MettlTest.class.getClass().getResource("/" + fileName).getPath());
workbook = new XSSFWorkbook(file);
sheet = workbook.getSheet(workSheetName);
try {
XSSFRow row;
XSSFCell cell;
lastRow = sheet.getPhysicalNumberOfRows();
lastCol = sheet.getRow(1).getLastCellNum();
sheetData = new String[lastRow - 1][lastCol];
for (int r = 1; r < lastRow; r++) {
row = sheet.getRow(r);
if (row != null) {
for (int c = 0; c < lastCol; c++) {
cell = row.getCell(c);
if (cell == null) {
sheetData[r][c] = null;
} else {
sheetData[r-1][c] = new DataFormatter().formatCellValue(cell);
}
}
}
}
return sheetData;
}
catch (final Exception e) {
throw e;
}
finally {
try {
file.close();
} catch (IOException io) {
Reporter.log("Unable to close File : " + fileName);
throw io;
}
}

Reading from excel file with blank cells to 2d array

I have a following code that reads logins and passwords from xls file starting from the second row(it skips column names) and writes it into a 2d array. But it only works if the sheet doesn't have blank cells in any of the rows. What should i do to make it work with empty cells?
private static Object[][] getUsersFromXls(String sheetName) {
final File excelFile = new File("src//resources//TestData.xls");
FileInputStream fileInputStream;
try {
fileInputStream = new FileInputStream(excelFile);
workbook = new HSSFWorkbook(fileInputStream);
} catch (IOException e) {
e.printStackTrace();
}
sheet = workbook.getSheet(sheetName);
final int numberOfRows = sheet.getLastRowNum();
final int numberOfColumns = sheet.getRow(0).getLastCellNum();
final String[][] xlsData = new String[numberOfRows][numberOfColumns];
String cellValue;
for (int i = 1; i <= numberOfRows; i++) {
final HSSFRow row = sheet.getRow(i);
for (int j = 0; j < numberOfColumns; j++) {
final HSSFCell cell = row.getCell(j);
final int cellType = cell.getCellType();
if (cellType == HSSFCell.CELL_TYPE_FORMULA) {
throw new RuntimeException("Cannot process a formula. Please change field to result of formula.");
} else {
cellValue = String.valueOf(cell);
xlsData[i - 1][j] = cellValue;
}
}
}
return xlsData;
}

how to compare two or more values in excel with values in li and report pass or fail in same excel using apache poi selenium webdriver java

I need to import 2 or more values from excel and compare the value which i have in my li's , the code i have used is
FileInputStream input=new FileInputStream(new File("TestCase.xls"));
HSSFWorkbook workbook=new HSSFWorkbook(input);
HSSFSheet sheet=workbook.getSheet("KeywordFramework");
System.out.println("i am in");
int rowNum = sheet.getLastRowNum() + 1;
System.out.println(rowNum);
int colNum = sheet.getRow(0).getLastCellNum();
System.out.println(colNum);
String data [][] = new String[rowNum][colNum];
for(int i =1 ; i< rowNum;i++)
{
System.out.println("1");
HSSFRow row = sheet.getRow(i);
for(int j = 0; j<= colNum;j++)
{
System.out.println("2");
HSSFCell cell = row.getCell(j);
String Cellvalue = cellToString(cell);
System.out.println("cellvalue === "+Cellvalue);
switch(j)
{
`case 1:
case 2:
ExpectedOP=Cellvalue;
System.out.println("Expected output (value to be compared) = "+ExpectedOP);
int LastRow = 1;
List <WebElement> we = driver.findElements(By.xpath(".//*[#id='stepList']/li"));//Getting list of elements in steplist ul
for(int i1=2;i1<=we.size();i1++)
{
String sr [] =new String [10];
sr [i1]=driver.findElement(By.xpath(".//*[#id='stepList']/li["+i1+"]")).getText().trim();//Getting required li text data (example : abc)
for (String j1:sr)
{
if(j1 != null)
{
String [] parts = sr [i1].split("/");//Spliting to get the required data
String parta = parts [0].trim();//Triming the whitespaces
System.out.println("Step value = "+parta);
if(ExpectedOP.equals(parta))//Comparing value in Excel with value got in excel
{
System.out.println("compare pass");
String status="PASS";
[Write into excel];
break;
}
else
{
System.out.println("compare pass");
String status="Fail";
[Write into excel];
break;
}//Close else
}//Close if j1 null
}//Close for j1
}//Close i1 for loop
}//Close Switch(j)
}}}//Close the rest`
The value of Excel is not getting incremented once i get the next value , i.e., say if the first value from excel was abc and abc is compared with the value in li1 which is abc and say pass , and for i1 for loop gets li2 value as xyz but still the cellvalue will be abc , i want the cell value to be xyz so that i can compare xyz value of cell with value in li2
Please refer below sample program to compare value from excel with site console output :
//CALL FIREFOX DRIVER TO OPEN IT
WebDriver driver = new FirefoxDriver();
driver.get("http://en.wikipedia.org/wiki/Software_testing");
String title = driver.getTitle();
System.out.println(title);
FileInputStream input = new FileInputStream("D:\\sel.xls");
int count=0;
HSSFWorkbook wb = new HSSFWorkbook(input);
HSSFSheet sh = wb.getSheet("sheet1");
HSSFRow row = sh.getRow(count);
String data = row.getCell(1).toString();
System.out.println(data);
FileOutputStream webdata = new FileOutputStream ("D:\\sel.xls");
if(title.equals(data))
{
row.createCell(10).setCellValue("TRUE");
wb.write(webdata);
}
else
{
row.createCell(11).setCellValue("FALSE");
wb.write(webdata);
}
driver.close();
wb.close();
input.close();
}
}

Categories

Resources