Arraylist and Iteration - java

I have an Excel File with Values in the Ranges C17:C40, D17:D40 and E17:E40.
Now I read with Apache Poi the first Range with a for each loop. My Problem is I want to include a Code something like this:
If C17 is empty go to the next range (in this case D17) and check if D17 ist empty. If not read every Cell from the List and put it into a new Array list.
I hope some of you understand me. Here is my code:
public static ArrayList<String> list = new ArrayList<>();
public static ArrayList<String> ForEachLoop() throws EncryptedDocumentException, FileNotFoundException, IOException {
Workbook readWorkbook = WorkbookFactory.create(new FileInputStream(FileChooser.FileChoose()) );
Sheet sheet = readWorkbook.getSheetAt(4);
DataFormatter dataFormatter = new DataFormatter();
String cellValue = null;
for (int i = 16; i < 40; i++) { //Statt 20 soll hier 40
Row row = sheet.getRow(i);
if(row == null) {
continue;
}
for (int j = 2; j < 4; j++) {
Cell cell = row.getCell(j);
list.add(dataFormatter.formatCellValue(cell));
if(cell == null) {
continue;
}
// cellValue = dataFormatter.formatCellValue(cell);
// System.out.print(cellValue + "\n");
}
}
return list;
}

Related

How to fetch duplicate records from excel and write into new file using java

I can read the data of one col 0 by using below code. I need to fetch the record for duplicate value present in col 0
FileInputStream fis = new FileInputStream(theNewestFile);
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet spreadsheet = workbook.getSheetAt(0);
XSSFRow row;
String cellValueMaybeNull;
List<Cell> cells = new ArrayList<Cell>();
for (int rowIndex = 0; rowIndex <= spreadsheet.getLastRowNum(); rowIndex++) {
row = (XSSFRow) spreadsheet.getRow(rowIndex);
if (row != null) {
int colIndex = 0;
Cell cell = row.getCell(colIndex);
if (cell != null) {
// Found column and there is value in the cell.
cellValueMaybeNull = cell.getStringCellValue();
// Do something with the cellValueMaybeNull here ...
System.out.println(cellValueMaybeNull);
}
}
}
Declare a Map and capture all the duplicates and print it later. If the list size is more than 1 then it is duplicate case scenario.
FileInputStream fis = new FileInputStream(theNewestFile);
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet spreadsheet = workbook.getSheetAt(0);
XSSFRow row;
String cellValueMaybeNull;
List<Cell> cells = new ArrayList<Cell>();
Map<String,List<String>> duplicateCheck = new HashMap<String,List<String>>();
for (int rowIndex = 0; rowIndex <= spreadsheet.getLastRowNum(); rowIndex++) {
row = (XSSFRow) spreadsheet.getRow(rowIndex);
if (row != null) {
int colIndex = 0;
Cell cell = row.getCell(colIndex);
if (cell != null) {
// Found column and there is value in the cell.
cellValueMaybeNull = cell.getStringCellValue();
// Do something with the cellValueMaybeNull here ...
if(duplicateCheck.get(cellValueMaybeNull) != null) {
duplicateCheck.get(cellValueMaybeNull).add(cellValueMaybeNull);
}
else {
List<String> list = new ArrayList<String>();
list.add(cellValueMaybeNull);
duplicateCheck.put(cellValueMaybeNull, list);
}
}
}
}
for(List<String> duplicateValue : duplicateCheck.values()) {
if(duplicateValue.size() > 1) {
System.out.println("Duplicate values :"+duplicateValue);
}
}

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

Trying to extract data and write to another spreadsheet comes up empty

The output file is created but only the first cell is written and nothing else. I tested it with system print and all the data that I want shows up in console but is not written to the worksheet.
public class excel_read_2 {
public static void main(String[] args)
{
try
{
FileInputStream file = new FileInputStream(new File("C:/Users/h.M/Desktop/20151007-110016_outgoing.xls")); //input
HSSFWorkbook workbook = new HSSFWorkbook(file);
HSSFSheet sheet = workbook.getSheetAt(0);
Workbook wb = new HSSFWorkbook();
Sheet sheet1 = wb.createSheet("new sheet");
FileOutputStream fileOut = new FileOutputStream("C:/Users/h.M/Desktop/workbook.xls"); //output
int rowcounter = 0;
for (int rowNum = 150; rowNum < 180; rowNum++) {
Row r = sheet.getRow(rowNum);
if (r == null) {
continue;
}
int lastColumn=6;
for (int cn = 0; cn < lastColumn; cn++) {
Cell c = r.getCell(cn, Row.RETURN_BLANK_AS_NULL);
if (c == null){
}
else if (c.getCellType() == HSSFCell.CELL_TYPE_STRING) {
Row row = sheet1.createRow((short)rowcounter);
Cell cell = row.createCell(cn);
row.createCell(cn).setCellValue(c.getStringCellValue());
System.out.println("The cell was a string \" " + c.getStringCellValue()+" \" ");
} else if (c.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
Row row = sheet1.createRow((short)rowcounter);
Cell cell = row.createCell(cn);
row.createCell(cn).setCellValue(c.getNumericCellValue());
System.out.println("The cell was a number " + c.getNumericCellValue());
}
}
rowcounter++;
}
wb.write(fileOut);
fileOut.close();
file.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Create the new row before you loop, then use it once per loop.
Row row = sheet1.createRow((short)rowcounter);
int lastColumn=6;
for (int cn = 0; cn < lastColumn; cn++) {
Cell c = r.getCell(cn, Row.RETURN_BLANK_AS_NULL);
if (c == null){
}
else if (c.getCellType() == HSSFCell.CELL_TYPE_STRING) {
Cell cell = row.createCell(cn);
cell.setCellValue(c.getStringCellValue());

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 deal with blank cells in excel files java

I am making a program where I am reading data from excel files and store them in tables. I have made the program using Apache POI and works fine. But when files have blank cells as the one here I have some problems. The program skip the blanks and read the next data. Could anyone help me how I would do it? I know that there are several posts for this issue but I have not found something useful for me.
The code for reading the data from excel file is the below. As you can see I have 3 types of data. How i would give the option for BLANK CELL?
// Create an ArrayList to store the data read from excel sheet.
List sheetData = new ArrayList();
FileInputStream fis = null;
try {
// Create a FileInputStream that will be use to read the
// excel file.
fis = new FileInputStream(strfullPath);
// Create an excel workbook from the file system
HSSFWorkbook workbook = new HSSFWorkbook(fis);
// Get the first sheet on the workbook.
HSSFSheet sheet = workbook.getSheetAt(0);
// store the data read on an ArrayList so that we can printed the
// content of the excel to the console.
Iterator rows = sheet.rowIterator();
while (rows.hasNext()) {
HSSFRow row = (HSSFRow) rows.next();
Iterator cells = row.cellIterator();
List data = new ArrayList();
while (cells.hasNext()) {
HSSFCell cell = (HSSFCell) cells.next();
data.add(cell);
}
sheetData.add(data);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
fis.close();
}
}
showExcelData(sheetData);
}
private static void showExcelData(List sheetData) {
// LinkedHashMap<String, String> tableFields = new LinkedHashMap();
for (int i = 0; i < sheetData.size(); i++) {
List list = (List) sheetData.get(i);
for (int j = 0; j < list.size(); j++) {
Cell cell = (Cell) list.get(j);
if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
System.out.print(cell.getNumericCellValue());
} else if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
System.out.print(cell.getRichStringCellValue());
} else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
System.out.print(cell.getBooleanCellValue());
} else if (cell.getCellType()== Cell.CELL_TYPE_BLANK ){
System.out.print(cell.toString());
}
if (j < list.size() - 1) {
System.out.print(", ");
}
}
System.out.println("");
}
}
}
Also I have read about workbook.setMissingCellPolicy(HSSFRow.RETURN_NULL_AND_BLANK);. Could this help me with my problem?
int maxNumOfCells = sheet.getRow(0).getLastCellNum(); // The the maximum number of columns
Iterator rows = sheet.rowIterator();
while (rows.hasNext()) {
HSSFRow row = (HSSFRow) rows.next();
Iterator cells = row.cellIterator();
List data = new ArrayList();
for( int cellCounter = 0
; cellCounter < maxNumOfCells
; cellCounter ++){ // Loop through cells
HSSFCell cell;
if( row.getCell(cellCounter ) == null ){
cell = row.createCell(cellCounter);
} else {
cell = row.getCell(cellCounter);
}
data.add(cell);
}
sheetData.add(data);
YOUR METHOD:
public static void showExcelData(List sheetData) {
// LinkedHashMap<String, String> tableFields = new LinkedHashMap();
for (int i = 0; i < sheetData.size(); i++) {
List list = (List) sheetData.get(i);
for (int j = 0; j < list.size(); j++) {
Cell cell = (Cell) list.get(j);
if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
System.out.print(cell.getNumericCellValue());
} else if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
System.out.print(cell.getRichStringCellValue());
} else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
System.out.print(cell.getBooleanCellValue());
} else if (cell.getCellType() == Cell.CELL_TYPE_BLANK) {
System.out.print("THIS IS BLANK");
}
if (j < list.size() - 1) {
System.out.print(", ");
}
}
System.out.println("");
}
}
Explanation:
int maxNumOfCells = sheet.getRow(0).getLastCellNum(); - This line will make sure that you were able to get the number of columns. Using the Row's method .getLastCellNum() on the next rows will result to unexpected number. Example on your on row 3 of your spreadsheet, the method will return 2 since the next value is null.
for( int cellCounter = 0
; cellCounter < maxNumOfCells
; cellCounter ++){ // Loop through cells
HSSFCell cell;
if( row.getCell(cellCounter ) == null ){
cell = row.createCell(cellCounter);
} else {
cell = row.getCell(cellCounter);
}
data.add(cell);
}
Looping through the cells. From cell 0 (Base 0) to the last cell number. If the cell was found null, basically, it would create the cell with a blank value. Lastly, adding the cell to your List.
Another solution if you don't know the size of your spreadsheet is to loop through row and column and compare the index of row and column with the previous one you parsed. If the increment is more than one you will create the missing intermediate cells.

Categories

Resources