Reading from excel file with blank cells to 2d array - java

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;
}

Related

how to read data from excel, having only one column

//method contains:
public Object[][] getExcelData(String excelLocation) {
Object[][] dataSet = null;
try {
file = new FileInputStream(excelLocation);
wrkbook = new XSSFWorkbook(file);
wrkbook.close();
sheet = wrkbook.getSheetAt(0);
// to get total active row count
int rowNum = sheet.getLastRowNum();
// to get total active column count
int colNum = sheet.getRow(0).getLastCellNum();
dataSet = new Object[rowNum][colNum];
for (int i = 0; i <rowNum; i++) {
XSSFRow row = sheet.getRow(i);
for (int j = 0; j <=colNum; j++) {
XSSFCell cell = row.getCell(j);
String value = String.valueOf(cell);
dataSet[i][j] = value;
}
}
return dataSet;
} catch (Exception e) {
e.printStackTrace();
}
return null;
// return null if for any exception
If you want to return the column values from the spreadsheet as a 2d array, change the signature of your method to return an array of type String[][], iterate over each row of the spreadsheet, adding the value of all of its columns to the array, and return the Array when you're done. I haven't tested this but it should be pretty close:
public static String[][] getDataSetAsArray(XSSFSheet pSheet) {
int iRowCount = pSheet.getLastRowNum();
int iColumnCount = pSheet.getRow(pSheet.getFirstRowNum()).getLastCellNum();
String[][] strDataVals = new String[iRowCount][iColumnCount];
for (int r = 0; r <= iRowCount; r++) {
XSSFRow row = pSheet.getRow(r);
for (int c = 0; c <= iColumnCount; c++) {
strDataVals[r][c] = row.getCell(c).getStringCellValue();
}
}
return strDataVals;
}

Not able to check in excel using Apache POI if specific cell as per row and column is empty in Selenium with Java

I'm trying to write data in excel while running my tests and in Excel Test Class I have written a code to check if specific row under column is empty then write data else increment the row by 1 and then check same and write data.
From another class I'm calling ExcelTest:
ExcelTest sfName = new ExcelTest("C:\\Users\\abc\\eclipse-workspace\\dgc\\src\\com\\dg\\base\\utility\\TestData.xlsx");
sfName.setCellData("Sheet1","SingleFactor Campaign",SFCampName);
ExcelTest Class
public class ExcelTest
{
public FileInputStream fis = null;
public FileOutputStream fos = null;
public XSSFWorkbook workbook = null;
public XSSFSheet sheet = null;
public XSSFRow row = null;
public XSSFCell cell = null;
String xlFilePath;
boolean isEmptyStringCell;
public ExcelTest(String xlFilePath) throws Exception
{
this.xlFilePath = xlFilePath;
fis = new FileInputStream(xlFilePath);
workbook = new XSSFWorkbook(fis);
fis.close();
}
public void setCellData(String sheetName, String colName, int rowNum, String value)
{
try
{
int col_Num = -1;
sheet = workbook.getSheet(sheetName);
row = sheet.getRow(0);
for (int i = 0; i < row.getLastCellNum(); i++)
{
if(row.getCell(i).getStringCellValue().trim().equals(colName))
{
col_Num = i;
}
}
sheet.autoSizeColumn(col_Num);
for(int j=2; j<7; j++)
{
row = sheet.getRow(j - 1);
if(row==null)
row = sheet.createRow(j - 1);
cell = row.getCell(col_Num);
isEmptyStringCell=cell.getStringCellValue().trim().isEmpty();
if (this.isEmptyStringCell)
{
cell = row.createCell(col_Num);
cell.setCellValue(value);
break;
}
else
{
j=j+1;
}
}
/*row = sheet.getRow(rowNum - 1);
if(row==null)
row = sheet.createRow(rowNum - 1);
cell = row.getCell(col_Num);
if(cell == null)
cell = row.createCell(col_Num);
cell.setCellValue(value);*/
System.out.println("The cell value is "+cell.getStringCellValue());
fos = new FileOutputStream(xlFilePath);
workbook.write(fos);
fos.close();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
If we remove the block comment(mentioned above in code and add then comment to this code listed below then it will just write data in cell whichever is provided while calling the function.
In below code I'm starting a loop till max 7 rows and then checking if the cell contains data then increment or write data and once it writes then exit the loop.
for(int j=2; j<7; j++)
{
row = sheet.getRow(j - 1);
if(row==null)
row = sheet.createRow(j - 1);
cell = row.getCell(col_Num);
isEmptyStringCell=cell.getStringCellValue().trim().isEmpty();
if (this.isEmptyStringCell)
{
cell = row.createCell(col_Num);
cell.setCellValue(value);
break;
}
else
{
j=j+1;
}
}
Expected: It should write data in a row which has no cell data.
Actual: It doesn't write anything.
I've found solution for the above question and only need to change few code and now it is working as expected:
for(int j=2; j<7; j++)
{
row = sheet.getRow(j - 1);
if(row==null)
row = sheet.createRow(j - 1);
cell = row.getCell(col_Num);
//it will check if cell contains no value then create cell and set value
if(cell == null)
{
cell = row.createCell(col_Num);
cell.setCellValue(value);
break;
}
}

read multiple excel sheet selenium-webdriver, java, eclipse

I want to run selenium-webdriver-java-eclipse, using excel file contains multiple excel sheets with different name(sheet1,sheet2,sheet3,...), i need a for loop help me to do that and read from this sheets.
public class ExcelDataConfig {
XSSFWorkbook wb;
XSSFSheet sheet = null;
public ExcelDataConfig(String Excelpath) throws IOException {
// TODO Auto-generated method stub
try {
File file = new File(Excelpath);
// Create an object of FileInputStream class to read excel file
FileInputStream fis = new FileInputStream(file);
wb = new XSSFWorkbook(fis);
} catch (Exception e) {
}
}
public String GetData(int sheetNumber, int Row, int Column) {
Iterator<Row> rowIt=sheet.rowIterator();
DataFormatter formatter = new DataFormatter();
XSSFCell cell = sheet.getRow(Row).getCell(Column);
String data = formatter.formatCellValue(cell);
return data;
}
public int GetRowCount(String sheetNumber) {
int row = wb.getSheet(sheetNumber).getLastRowNum();
row = row + 1;
return row;
}
}
try something like this, it is working for me you need to add the sheet numbers and cell numbers at the places of k and j
enter code here
String filePath="C:\\Users\\USER\\Desktop\\Book1.xlsx";// file path
FileInputStream fis=new FileInputStream(filePath);
Workbook wb=WorkbookFactory.create(fis);
ArrayList<String> ls=new ArrayList<String>();
for(int k=0; k<=3;k++)//k =sheet no
{
Sheet sh=wb.getSheetAt(k);
System.out.println(sh);
// int count=0;
for(int i=0;i<=sh.getLastRowNum();i++)
{
System.out.println("row no:"+i);
for(int j=0; j<=4;j++)//j=column no
{
try {
String values=sh.getRow(i).getCell(j).getStringCellValue().trim();
System.out.println(values);
//condetions
/* if(values.contains("condtn1"))
{
System.out.println("Value of cell "+values+" ith row "+(i+1));
ls.add(values);
count++;
}
if(values.contains("condn2"))
{
System.out.println("Value of cell "+values+" ith row "+(i+1));
ls.add(values);
count++;
}*/
}catch(Exception e){
}
}
}
}
}
}
Please try writing similar to something like this:
for (int i = startRow; i < endRow + 1; i++) {
for (int j = startCol; j < endCol + 1; j++) {
testData[i - startRow][j - startCol] = ExcelWSheet.getRow(i).getCell(j).getStringCellValue();
Cell cell = ExcelWSheet.getRow(i).getCell(j);
testData[i - startRow][j - startCol] = formatter.formatCellValue(cell);
}
}
Terms used in method are pretty self explanatory. Let us know if you get stuck or need more info.

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;
}
}

Update excel file base on the output from textarea

My code imports the excel file then put a certain column in to a textarea
I want to know how would i modify the excel file if for example i edited something on the textarea that edit should be saved on the excel file
String excelFilePath = "sample.xlsx";
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(new File(excelFilePath));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
Workbook workbook = null;
try {
workbook = new XSSFWorkbook(inputStream);
} catch (IOException e1) {
e1.printStackTrace();
}
Sheet firstSheet = workbook.getSheetAt(0);
Iterator<Row> iterator = firstSheet.iterator();
while (iterator.hasNext()) {
Row nextRow = iterator.next();
Iterator<Cell> cellIterator = nextRow.cellIterator();
Iterator<Cell> scellIterator = nextRow.cellIterator();
cellIterator.next();
scellIterator.next();
scellIterator.next();
Cell topicsCell = cellIterator.next();
Cell topicSentimentCell =scellIterator.next();
String cellContents = topicsCell.getStringCellValue();
String scellContents = topicSentimentCell.getStringCellValue();
String[] topics = cellContents.split(";");
String[] topicSentiment = scellContents.split(";");
ArrayList<String> tpc = new ArrayList<>();
ArrayList<String> topicsents = new ArrayList<>();
for(int i = 0; i < topics.length; i++) {
topics[i] = topics[i].trim();
tpc.add(topics[i]);
for (int indx = 0; indx < tpc.size(); indx++) {
textArea.append(tpc.get(indx)+"\n");
}
}
for(int si = 0; si < topicSentiment.length; si++) {
topicSentiment[si] = topicSentiment[si].trim();
topicsents.add(topicSentiment[si]);
for (int index = 0; index < topicsents.size(); index++) {
// textArea.append(topicsents.get(index)+"\n");
System.out.print(topicsents+"\n");
}
}
}
try {
inputStream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
Open a file as XSSFWorkbook
Open a XSSFSheet of the workbook
Make some changes in the sheet. For example change the value of a XSSFCell
Save the changes by workbook.write()
Example
// Open workbook and sheet
final XSSFWorkbook workbook = new XSSFWorkbook(new File("filename.xlsx"));
final XSSFSheet sheet = workbook.getSheetAt(0);
// Iterate rows
final int firstRowNumber = sheet.getFirstRowNum();
final int lastRowNumber = sheet.getLastRowNum();
for (int rowNumber = firstRowNumber; rowNumber < lastRowNumber; rowNumber++ ) {
final XSSFRow row = sheet.getRow(rowNumber);
if (row == null) continue;
// Iterate columns
final int firstColumnNumber = row.getFirstCellNum();
final int lastColumnNumber = row.getLastCellNum();
for (int columnNumber = firstColumnNumber; columnNumber < lastColumnNumber; columnNumber++ ) {
final XSSFCell cell = row.getCell(firstColumnNumber);
if (cell == null) continue;
// Make some changes
cell.setCellValue("new Value");
}
}
// Save changes
workbook.write(new FileOutputStream("newFilename.xlsx"));

Categories

Resources