Hi how can i create dynamic objects in a loop to store multiple values in the object. Then access those objects to manipulate.
Is it possible to give dynamic variable names for object creation. Can i give dynamic values of variable on the left hand side of an assignment. Please ask me to edit if the question is not clear, if solution already available please point me out to that.
package poi;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ExcelRead_UsingMember {
public static int C, R, i;
public static double ID;
private static final String FILE_READ = "C:/Users/m93162/ApachePOI_Excel_Workspace/MyFirstExcel.xlsx";
//private static final String FILE_WRITE = "C:/Users/m93162/ApachePOI_Excel_Workspace/WriteExcel.xlsx";
public static void main(String[] args) {
List<Member> listOfMembers = new ArrayList<Member>();
try {
FileInputStream excelFile = new FileInputStream(new File(FILE_READ));
Workbook workbook = new XSSFWorkbook(excelFile);
Sheet datatypeSheet = workbook.getSheetAt(0);
Iterator<Row> iterator = datatypeSheet.iterator();
while (iterator.hasNext()) {
Row currentRow = iterator.next();
Iterator<Cell> cellIterator = currentRow.iterator();
int i=0;
while (cellIterator.hasNext()) {
Member [member+i] = new Member();
QUESTION: I want to create dynamic objects here and store the values below dynamically. How to approach this.
Cell currentCell = cellIterator.next();
if (currentCell.getCellTypeEnum() == CellType.STRING) {
System.out.print(currentCell.getStringCellValue() + "--");
} else if (currentCell.getCellTypeEnum() == CellType.NUMERIC) {
System.out.print(currentCell.getNumericCellValue() + "--");
}
}
System.out.println();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
You can use map.
DynamicObject
DynamicObject {
prvate Map<String, Object> map = new HashMap();
public void addPropery(String key, Object value) {
map.put(key, value);
}
}
Your code
private void processRow(Row row) {
while (cellIterator.hasNext()) {
dynamicObjects[member+i] = new DynamicObject();
DynamicObject dynamicObject = dynamicObjects[member+i];
Cell currentCell = cellIterator.next();
if (currentCell.getCellTypeEnum() == CellType.STRING) {
System.out.print(currentCell.getStringCellValue() + "--");
dynamicObject.addProperty("stringField", currentCell.getStringCellValue());
} else if (currentCell.getCellTypeEnum() == CellType.NUMERIC) {
System.out.print(currentCell.getNumericCellValue() + "--");
dynamicObject.addProperty("numericField", currentCell.getNumericCellValue());
}
}
}
Then you can traverse keys of the map to get all possible values. You can also store other objects(for example, as nested maps) inside the map as values.
Related
package parser;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import org.apache.poi.xwpf.usermodel.IBodyElement;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
public class App {
public static void main(String[] args) {
List<List<List<String>>> tablesResults = new LinkedList<>();
try {
XWPFDocument doc = new XWPFDocument(new FileInputStream("filename"));
List<IBodyElement> documentBody = doc.getBodyElements();
for (IBodyElement i: documentBody){
if (i.getElementType() == org.apache.poi.xwpf.usermodel.BodyElementType.TABLE){
XWPFTable table = (XWPFTable) i;
List<XWPFTableRow> tableRows = table.getRows();
List<List<String>> tableList = new LinkedList<>();
for (XWPFTableRow r: tableRows){
List<String> rowList = new LinkedList<>();
for (XWPFTableCell cell: r.getTableCells()){
rowList.add(cell.getText());
}
tableList.add(rowList);
}
tablesResults.add(tableList);
}
}
for (List<List<String>> table: tablesResults){
for(List<String> row: table){
for(String cell: row){
System.out.print(cell + ", ");
}
System.out.println();
}
System.out.println("-------------------------");
}
} catch (IOException ex) {
System.out.println("Exception:");
System.out.println(ex.toString());
}
}
}
I am not able to extract the checkboxes from the tabular cells and also another table. at present I am using Apache poi, I need your suggestion and help to parse the data from a word document, in the next step I am going to compare this tabular data with another word document
picture of the table
This code tries to iterate over an excel file and load the data to a List<List<String>> but it throws java.lang.NullPointerException at resultList.add(rrow) but it is not clear what is the problem with it:
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ReadExcel {
public List<List<String>> resultList;
public List<List<String>> ReadExcelToList(String csvPath) throws IOException {
try {
FileInputStream excelFile = new FileInputStream(csvPath);
Workbook workbook = new XSSFWorkbook(excelFile);
System.out.println(workbook.getSheetName(0));
Sheet datatypeSheet = workbook.getSheetAt(0);
Iterator<Row> iterator = datatypeSheet.iterator();
while (iterator.hasNext()) {
Row currentRow = iterator.next();
Iterator<Cell> cellIterator = currentRow.iterator();
List<String> rrow = new ArrayList<>();
while (cellIterator.hasNext()) {
Cell currentCell = cellIterator.next();
switch (currentCell.getCellType()) {
case Cell.CELL_TYPE_STRING:
rrow.add(currentCell.getStringCellValue());
break;
case Cell.CELL_TYPE_NUMERIC:
rrow.add(String.valueOf(currentCell.getNumericCellValue()));
break;
}
}
resultList.add(rrow);
}
} catch (Exception e) {
e.printStackTrace();
}
return resultList;
}
}
java.lang.NullPointerException
at ReadExcel.readExcelToList(ReadExcel.java:40)
at BasicCSVReader.main(BasicCSVReader.java:35)
Your resultList was never created (it's null). You can fix it by defining it as follows:
public List<List<String>> resultList = new ArrayList<>();
I am using Apache POI API to read Excel file and check the quantity of products available or not. I am successfully reading excel file using below code but I am unable to read the specific cell (Quantity Column) to check weather asked product is available or not
package practice;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;
public class ReadingExcel {
private static String brand = "Nike";
private static String shoeName = "Roshe One";
private static String colour = "Black";
private static String size = "9.0";
private static String quantity;
public static void main(String [] args){
try {
FileInputStream excelFile = new FileInputStream(new File("C:\\Users\\admin\\Downloads\\Project\\assets\\Shoe_Store_Storeroom.xlsx"));
Workbook workbook = new XSSFWorkbook(excelFile);
Sheet datatypeSheet = workbook.getSheetAt(0);
DataFormatter dataFormatter = new DataFormatter();
Iterator<Row> iterator = datatypeSheet.iterator();
while (iterator.hasNext()) {
Row currentRow = iterator.next();
Iterator<Cell> cellIterator = currentRow.iterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
String cellValue = dataFormatter.formatCellValue(cell);
System.out.print(cellValue + "\t\t");
}
System.out.println();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
this is my excel file
using opencsv 4.1 i do this
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
...
try (InputStream excelFile = new FileInputStream(new File(fileName));
Workbook wb = new XSSFWorkbook(excelFile);) {
for (int numSheet = 0; numSheet < wb.getNumberOfSheets(); numSheet++) {
Sheet xssfSheet = wb.getSheetAt(numSheet);
xssfSheet.forEach(row -> {
Cell cell = row.getCell(0);
if (cell != null) {
if(StringUtils.isNumeric(cell.getStringCellValue())){
// Use here cell.getStringCellValue()
}
}
});
}
}
Use below for loop:
for(int r=sh.getFirstRowNum()+1; r<=sh.getLastRowNum(); r++){ //iterating through all the rows of excel
Row currentRow = sh.getRow(r); //get r'th row
Cell quantityCell = currentRow.getCell(4); //assuming your quantity cell will always be at position 4; if that is not the case check for the header value first
String currentCellValue = quantityCell.getStringCellValue();
if(currentCellValue.equalsIgnoreCase(<value you want to campare with>))
//<do your further actions here>
else
//do your further actions here
}
I am getting an error message when I hover over the 'CELL_TYPE_****' methods in the method getCellData(), saying that 'the static field "CELL_TYPE_***" should be accessed in a static way' and a strike line over them.
package excelSelenium;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class seleniumIntg {
XSSFWorkbook workbook = null;
XSSFSheet sheet = null;
XSSFRow Row = null;
XSSFCell Cell = null;
WebDriver driver = null;
#Test(dataProvider = "getData")
public void doLogin(String username, String password)
{
System.setProperty("webdriver.chrome.driver","C://testing/chromedriver_win32/chromedriver.exe" );
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.get("https://login.yahoo.com/config/login?.src=fpctx&.intl=in&.lang=en-IN&.done=https://in.yahoo.com/%3fp=us");
driver.findElement(By.xpath("//input[#id='login-username']")).sendKeys(username);
driver.findElement(By.xpath("//div[#class='mbr-login-submit']/button")).click();
driver.findElement(By.xpath("//input[#id='login-passwd']")).sendKeys(password);
}
#DataProvider
public Object[][] getData() throws IOException
{
FileInputStream fis = new FileInputStream("C://Users/Gaurav/Documents/testid.xlsx");
workbook = new XSSFWorkbook(fis);
sheet = workbook.getSheet("sheet1");
int rowCount = sheet.getFirstRowNum()+sheet.getLastRowNum()+1;
int colCount = sheet.getRow(0).getLastCellNum();
System.out.println("Row count is:" +rowCount+ "Col count is:" +colCount);
Object[][] data = new Object[rowCount-1][colCount];
for(int rNum = 2; rNum<=rowCount; rNum++)
for(int cNum = 0; cNum<colCount; cNum++)
{
System.out.println(getCellData("sheet1",cNum,rNum));
data[rNum-2][cNum]=getCellData("sheet1",cNum,rNum);
}
return data;
}
public String getCellData(String sheetName, int colNum, int rowNum)
{
try{
if(rowNum<=0)
return "";
int index = workbook.getSheetIndex(sheetName);
if(index == -1)
return "";
sheet =workbook.getSheetAt(index);
Row = sheet.getRow(rowNum-1);
if(Row==null)
return "";
Cell = Row.getCell(colNum);
if(Cell==null)
return "";
else if(Cell.getCellType()==Cell.CELL_TYPE_STRING)
return Cell.getStringCellValue();
else if(Cell.getCellType()==Cell.CELL_TYPE_NUMERIC||Cell.getCellType()==Cell.CELL_TYPE_FORMULA)
{String CellText = String.valueOf(Cell.getNumericCellValue());
return CellText;}
else if(Cell.getCellType()==Cell.CELL_TYPE_BLANK)
return "";
else return String.valueOf(Cell.getBooleanCellValue());
}
catch(Exception e)
{
e.printStackTrace();
return "row"+rowNum+"col"+colNum+"Does not exist";
}
}
// TODO Auto-generated method stub
}
In instructions such as :
else if(Cell.getCellType()==Cell.CELL_TYPE_STRING)
despite appearances, Cell is an instance and not a class as you declare this field in your class:
XSSFCell Cell = null;
But static fields and methods have no need to be prefixed by an instance to call them but by the class.
So you should prefix the static fields you are referencing like that :
else if(Cell.getCellType()==XSSFCell.CELL_TYPE_STRING)
To avoid this kind of misleading code that gives the impression that you are using as prefix an instance while you are using actually a class, follow the Java code conventions that say among other things that variable names should start by a lowercase character.
This is better :
XSSFCell cell = null;
...
else if(cell.getCellType() == XSSFCell.CELL_TYPE_STRING)
As a side note, the CELL_TYPE_STRING static field is deprecated since POI 3.15 beta 3.
You are advised to use the enum org.apache.poi.ss.usermodel.CellType.STRING instead of.
Well, first of all you should rename your variables, so that they start with lower-case letters (e.g. cell instead of Cell) to avoid confusion.
So cell is an instance of class XSSFCell which inherits from Cell.
The static fields e.g. CELL_TYPE_STRING are declared in the class Cell
: so you should use Cell.CELL_TYPE_STRING instead of cell.CELL_TYPE_STRING
I have spent countless hours trying to find a solution to this. I have tried Apache POI, JExcel and JXLS but no where have I found code to successfully read checkbox (form control) values.
If anyone has found a working solution then it would be great if you could share it here. Thanks!
UPDATE
I have written code that reads the checkbox but it cannot determine whether it is checked or not.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;
import org.apache.poi.hssf.eventusermodel.HSSFEventFactory;
import org.apache.poi.hssf.eventusermodel.HSSFListener;
import org.apache.poi.hssf.eventusermodel.HSSFRequest;
import org.apache.poi.hssf.record.CommonObjectDataSubRecord;
import org.apache.poi.hssf.record.ObjRecord;
import org.apache.poi.hssf.record.Record;
import org.apache.poi.hssf.record.SubRecord;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
public class App {
private static final String path = "C:\\test.xls";
private static final String Workbook = "Workbook";
private static void readExcelfile() {
FileInputStream file = null;
try {
file = new FileInputStream(new File(path));
// Get the workbook instance for XLS file
HSSFWorkbook workbook = new HSSFWorkbook(file);
// Get first sheet from the workbook
HSSFSheet sheet = workbook.getSheetAt(0);
// Iterate through each rows from first sheet
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
// For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch (cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t\t");
break;
}
}
System.out.println();
}
// file.close();
// FileOutputStream out = new FileOutputStream(
// new File(path));
// workbook.write(out);
// out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (file != null)
file.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
private static void readCheckbox() {
FileInputStream file = null;
InputStream istream = null;
try {
file = new FileInputStream(new File(path));
POIFSFileSystem poifs = new POIFSFileSystem(file);
istream = poifs.createDocumentInputStream(Workbook);
HSSFRequest req = new HSSFRequest();
req.addListenerForAllRecords(new EventExample());
HSSFEventFactory factory = new HSSFEventFactory();
factory.processEvents(req, istream);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (file != null)
file.close();
if (istream != null)
istream.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public static void main(String[] args) {
System.out.println("ReadExcelFile");
readExcelfile();
System.out.println("ReadCheckbox");
readCheckbox();
}
}
class EventExample implements HSSFListener {
public void processRecord(Record record) {
switch (record.getSid()) {
case ObjRecord.sid:
ObjRecord objRec = (ObjRecord) record;
List<SubRecord> subRecords = objRec.getSubRecords();
for (SubRecord subRecord : subRecords) {
if (subRecord instanceof CommonObjectDataSubRecord) {
CommonObjectDataSubRecord datasubRecord = (CommonObjectDataSubRecord) subRecord;
if (datasubRecord.getObjectType() == CommonObjectDataSubRecord.OBJECT_TYPE_CHECKBOX) {
System.out.println("ObjId: "
+ datasubRecord.getObjectId() + "\nDetails: "
+ datasubRecord.toString());
}
}
}
break;
}
}
}
Sorry for the late reply, but I ran into the same. I found a trick to determine the checkbox state.
In your example you ar looping over the SubRecords and you examine the CommonObjectDataSubRecord. But the value for the checkbox can be found in the one of the SubRecord.UnknownSubRecord. This is unfortunately a private class so you cannot call any method on it, but the toString() reveals the data, and with a little regex the value can be found. So using the code below I managed to retrieve the state of the checkbox:
Pattern p = Pattern.compile("\\[sid=0x000A.+?\\[0(\\d),");
if (!(subRecord instanceof CommonObjectDataSubRecord)) {
Matcher m = p.matcher(subRecord.toString());
if (m.find()) {
String checkBit = m.group(1);
if (checkBit.length() == 1) {
boolean checked = "1".equals(checkBit);
checkBox.setChecked(checked);
}
}
}
Now my challenge is to retrieve the checkbox value in a xlsx file...