I want to get data to List and display it.But out put display 4 times.
My excel file containing 4 data.
I want to get one record. My code is
public static List readDataFromExcel() throws IOException{
String filename = "path";
List sheetData = new ArrayList();
FileInputStream fis = null;
try {
fis = new FileInputStream(filename);
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheetAt(0);
Iterator rows = sheet.rowIterator();
while (rows.hasNext()) {
XSSFRow row = (XSSFRow) rows.next();
Iterator cells = row.cellIterator();
List data = new ArrayList();
while (cells.hasNext()) {
XSSFCell cell = (XSSFCell) cells.next();
String value=" ";
switch (cell.getCellType())
{
case Cell.CELL_TYPE_NUMERIC:
value = BigDecimal.valueOf(cell.getNumericCellValue()).toPlainString();
data.add(value);
break;
case Cell.CELL_TYPE_STRING:
value=cell.getStringCellValue();
data.add(value);
break;
case Cell.CELL_TYPE_BLANK:
value = " ".toString();
data.add(value);
break;
case Cell.CELL_TYPE_BOOLEAN:
value = Boolean.valueOf(cell.getBooleanCellValue()).toString();
data.add(value);
break;
}
sheetData.add(data);
}
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return sheetData;
}
Main methods
public static void main(String[] args) throws IOException {
List serverdetailsList = ReadDataFromExcel.readDataFromExcel();
List oneserverdetailsList = new ArrayList();
for (int i = 0; i < serverdetailsList.size(); i++) {
System.out.println(serverdetailsList.get(i));
}
}
Out put image
Excel ScrenShot
I see you are adding the inner ArrayList(data) to the main arrayList (sheetdata) as many as the number of times you find a cell.
The approach should have been
while (rows.hasNext()) {
XSSFRow row = (XSSFRow) rows.next();
Iterator cells = row.cellIterator();
List data = new ArrayList();
while (cells.hasNext()) {
XSSFCell cell = (XSSFCell) cells.next();
String value=" ";
switch (cell.getCellType())
{
case Cell.CELL_TYPE_NUMERIC:
value = BigDecimal.valueOf(cell.getNumericCellValue()).toPlainString();
data.add(value);
break;
case Cell.CELL_TYPE_STRING:
value=cell.getStringCellValue();
data.add(value);
break;
case Cell.CELL_TYPE_BLANK:
value = " ".toString();
data.add(value);
break;
case Cell.CELL_TYPE_BOOLEAN:
value = Boolean.valueOf(cell.getBooleanCellValue()).toString();
data.add(value);
break;
}
//sheetData.add(data);
}
sheetData.add(data);
fis.close();
}
You can use 2 for each loops
for(ArrayList innerList :serverdetailsList)
{for(Object cellData:innerList )
{
if(cellData.toString().equalsIgnoreCase("OS1")){
//Your operation
}
}
}
Hope this is what you are looking for!!
Related
This is my table
Name
Age
Marsel
22
Lewis
33
Andrew
23
Harry
45
I need to display Harry's name on the console with his age 45
'''
public class Main {
public static Scanner in = new Scanner(System.in);
public static void main(String[] args) throws IOException {
FileInputStream file = new FileInputStream(new File("C:\\Users\\User\\Desktop\\school.xlsx"));
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheet("Director");
List<Double> list = new ArrayList<>();
Iterator iterator=sheet.iterator();
while (iterator.hasNext()) {
XSSFRow row = (XSSFRow) iterator.next();
Iterator cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
XSSFCell cell = (XSSFCell) cellIterator.next();
switch (cell.getCellType()) {
case NUMERIC:
list.add(cell.getNumericCellValue());
break;
}
}
}
Double max=Collections.max(list);
int ind=list.indexOf(max);
while(iterator.hasNext()){
XSSFRow row = sheet.getRow(ind+1);
Iterator cellIterator=row.cellIterator();
System.out.println(row);
while(cellIterator.hasNext())
{
XSSFCell cell=(XSSFCell) cellIterator.next();
switch(cell.getCellType())
{
case STRING: System.out.print(cell.getStringCellValue()); break;
case NUMERIC: System.out.print(cell.getNumericCellValue());break;
case BOOLEAN: System.out.print(cell.getBooleanCellValue()); break;
}
}
}
}
}
'''
You can only walk an iterator once. If you want to find the row again, you would have to read the file again from the top. The iterator you are using already return false on iterator.hasNext (). So the second loop will not be entered at all.
Please suggest me some code for the reading and executing approx 300 URLs from excel file in selenium.
I have done something like this:
public static void main(String[] args) {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver", "C:\\Users\\Jatin\\Downloads\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://example.com/");
List<WebElement> getLinks = driver.findElements(By.tagName("a"));
// to get the list of urls from the website
System.out.println(getLinks.size());
//fetch data from excel
try {
File excel = new File("C:\\Users\\Jatin\\Documents\\Output.xlsx");
FileInputStream fis = new FileInputStream(excel);
XSSFWorkbook book = new XSSFWorkbook(fis);
XSSFSheet sheet = book.getSheetAt(0);
Iterator<Row> itr = sheet.iterator();
// Iterating over Excel file in Java
while (itr.hasNext()) {
Row row = itr.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch (cell.getCellType()) {
case STRING:
System.out.print(cell.getStringCellValue() + "\t");
break;
case NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t");
break;
case BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t");
break;
default:
}
}
System.out.println("");}
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
I need to read the contents of an excel file and dump the same into a text file. I am able to read the contents from the file.
I created a List excelData = new ArrayList(); which should hold the row data present in the excel sheet. But each column is of a different data type. How do I save the contents into the List ?
List excelData = new ArrayList();
try {
FileInputStream file = new FileInputStream(new File("H:\\Docs\\Medical Data Record\\MedicalRecord2015.xlsx"));
XSSFWorkbook wb = new XSSFWorkbook(file);
XSSFSheet ws = wb.getSheetAt(0);
Iterator<Row> itr = ws.iterator();
while (itr.hasNext()) {
Row row = itr.next();
Iterator<Cell> itrCell = row.cellIterator();
while (itrCell.hasNext()) {
Cell cell = itrCell.next();
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
double val = cell.getNumericCellValue();
break;
case Cell.CELL_TYPE_STRING:
String txtval = cell.getStringCellValue();
break;
}
}
}
Thanks
Seems you need not List, but List<List<Object>> here:
List<List<Object>> excelData = new ArrayList<>();
try {
//...
while (itr.hasNext()) {
Row row = itr.next();
List<Object> dataRow = new ArrayList<>();
excelData.add(dataRow);
Iterator<Cell> itrCell = row.cellIterator();
while (itrCell.hasNext()) {
Cell cell = itrCell.next();
if (cell == null) {
dataRow.add(null);
continue;
}
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
dataRow.add(cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
dataRow.add(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BOOLEAN:
dataRow.add(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_BLANK:
dataRow.add("");
break;
default:
dataRow.add(cell);
}
}
}
Now, excelData contains List of rows represented as List<Object>, and can be easily saved to text file row by row. To achieve better consistency, you need also check another types of cell, like Cell.CELL_TYPE_BOOLEAN or null.
I am trying to read the data from an excel file which has formulas and writing the data to a particular column of another excel but by using the below code, i am getting an error message like : Cannot Convert from void to HSSFCell at line 68.
#Test
public void SampleCustNumFormat() throws Exception {
String [] myXL = getExcelData();
//Write Data into Excel.
//See what has been read from Excel
System.out.println (" Before Loop " + myXL[1]);
for (int i=0; i<xRows; i++){
System.out.println (" Cust Num " + myXL[i]);
}
FileOutputStream out = new FileOutputStream ("C:\\SCE docs\\Automation\\TestExcelData.xls");
HSSFWorkbook myWB = new HSSFWorkbook();
HSSFSheet sheet = myWB.getSheetAt(0);
for (int k=1; k<=sheet.getLastRowNum(); k++)
{
HSSFCell cell = sheet.getRow(1).createCell(2).setCellValue(myXL[k]);
}
myWB.write(out);
out.close();
}
public String [] getExcelData() throws Exception{
String [] tabArray=null;
FileInputStream fi = new FileInputStream("C:\\SCE docs\\Automation\\CustomerAccount_Information.xls");
HSSFWorkbook myWB = new HSSFWorkbook(fi);
HSSFSheet mySheet = myWB.getSheetAt(0);
FormulaEvaluator evaluator = myWB.getCreationHelper().createFormulaEvaluator();
xRows = mySheet.getLastRowNum()+1;
tabArray = new String [xRows];
for (int i=0;i<xRows;i++)
{
HSSFRow row = mySheet.getRow(i);
HSSFCell cell = row.getCell(3);
CellValue cellValue = evaluator.evaluate(cell);
String value = evaluateFormula(cellValue);
tabArray[i]=value;
}
return tabArray;
}
private String evaluateFormula(CellValue cellValue) throws Exception{
int type = cellValue.getCellType();
Object result=null;
switch (type) {
case HSSFCell.CELL_TYPE_BOOLEAN:
result = cellValue.getBooleanValue();
break;
case HSSFCell.CELL_TYPE_NUMERIC:
result = cellValue.getNumberValue();
break;
case HSSFCell.CELL_TYPE_STRING:
result = cellValue.getStringValue();
break;
case HSSFCell.CELL_TYPE_BLANK:
break;
case HSSFCell.CELL_TYPE_ERROR:
break;
// CELL_TYPE_FORMULA will never happen
case HSSFCell.CELL_TYPE_FORMULA:
break;
}
return result.toString();
}
}
These lines are causing the trouble:
for (int k=1; k<=sheet.getLastRowNum(); k++)
{
HSSFCell cell = sheet.getRow(1).createCell(2).setCellValue(myXL[k]);
}
Here you are getting the first row out of the sheet, creating a cell at index 2 and then setting the cell value... and assigning all of that to a Cell! However, setCellValue returns a void (as seen in the API). So basically, you need to split those lines into two like this:
for (int k=1; k<=sheet.getLastRowNum(); k++)
{
HSSFCell cell = sheet.getRow(1).createCell(2);
cell.setCellValue(myXL[k]);
}
Doing it this way, you'll first create the cell and assign that to cell. Then, you can set the value.
Edit: Alternatively, you can (as pointed out by Sankumarsingh) just not assign that value and do it all in one line like this:
for (int k=1; k<=sheet.getLastRowNum(); k++)
{
sheet.getRow(1).createCell(2).setCellValue(myXL[k]);
}
After Akoksis, I have to reframe your programe. please check it out whether its working or not for you
#Test
public void SampleCustNumFormat() throws Exception {
FileInputStream fi = new FileInputStream("C:\\SCE docs\\Automation\\CustomerAccount_Information.xls");
HSSFWorkbook myWB = new HSSFWorkbook(fi);
HSSFSheet mySheet = myWB.getSheetAt(0);
String [] myXL = getExcelData(myWB);
//See what has been read from Excel
System.out.println (" Before Loop " + myXL[1]);
for (int i=0; i<xRows; i++){
System.out.println (" Cust Num " + myXL[i]);
}
FileInputStream file = new FileInputStream("C:\\SCE docs\\Automation\\TestExcelData.xls");
HSSFWorkbook wb = new HSSFWorkbook(file);
for (int k=1; k<=sheet.getLastRowNum(); k++){
wb.getSheet(0).getRow(1).createCell(2).setCellValue(myXL[k]);
}
//Write Data into Excel.
FileOutputStream out = new FileOutputStream ("C:\\SCE docs\\Automation\\TestExcelData.xls");
wb.write(out);
out.close();
}
public String [] getExcelData(HSSFWorkbook myWB) throws Exception{
String [] tabArray=null;
HSSFSheet mySheet = myWB.getSheetAt(0);
FormulaEvaluator evaluator = myWB.getCreationHelper().createFormulaEvaluator();
xRows = mySheet.getLastRowNum()+1;
tabArray = new String [xRows];
for (int i=0;i<xRows;i++){
HSSFRow row = mySheet.getRow(i);
HSSFCell cell = row.getCell(3);
CellValue cellValue = evaluator.evaluate(cell);
String value = evaluateFormula(cellValue);
tabArray[i]=value;
}
return tabArray;
}
private String evaluateFormula(CellValue cellValue) throws Exception{
int type = cellValue.getCellType();
Object result=null;
switch (type) {
case HSSFCell.CELL_TYPE_BOOLEAN:
result = cellValue.getBooleanValue();
break;
case HSSFCell.CELL_TYPE_NUMERIC:
result = cellValue.getNumberValue();
break;
case HSSFCell.CELL_TYPE_STRING:
result = cellValue.getStringValue();
break;
case HSSFCell.CELL_TYPE_BLANK:
break;
case HSSFCell.CELL_TYPE_ERROR:
break;
// CELL_TYPE_FORMULA will never happen
case HSSFCell.CELL_TYPE_FORMULA:
break;
}
return result.toString();
}
}
i am using APACHE POI to read the data from excel files. I would like to store them in lists (like list in c) the result because afterwards I will try to store them in mysql database calling only list[0], list[1] for example. What i will try to do is make this list and after i will use jdbc driver and giving this list to make the tables in mysql.
The code for reading excel file is the above:
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
public class readexcel{
#SuppressWarnings({ "unchecked", "unchecked" })
public static void main(String[] args) throws Exception {
//
// An excel file name. You can create a file name with a full
// path information.
//
String filename = "C:\\Users\\xxx\\Documents\\test.xls";
//
// 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(filename);
//
// 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);
//
// When we have a sheet object in hand we can iterator on
// each sheet's rows and on each row's cells. We 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) {
//
// Iterates the data and print it out to the console.
//
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());
}
if (j < list.size() - 1) {
System.out.print(", ");
}
}
System.out.println("");
}
}
}
What i have to add to do what i explain you?
initialize the array list way before starting to iterate the sheet,
the array list must have a scope to persist anywhere in the row and column iteration of the excel sheet .
ArrayList myList = new ArrayList()
the put these line inside the cell iteration loop which is being performed n row basis
if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC)
{
System.out.print(cell.getNumericCellValue());
myList.add(cell.getNumericCellValue());
}
else if (cell.getCellType() == Cell.CELL_TYPE_STRING)
{
System.out.print(cell.getRichStringCellValue());
myList.add(cell.getRichStringCellValue());
}
else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN)
{
System.out.print(cell.getBooleanCellValue());
myList.add(cell.getBooleanCellValue());
}
now you process this list to insert data in to your DataBase
I found this function usable
public static ArrayList<ArrayList<String>> GetExcelTableInto2DArrayListString(String excelFile, boolean debug){
ArrayList<ArrayList<String>> OUT = new ArrayList<ArrayList<String>>();
File myFile = new File(excelFile);
FileInputStream fis = null;
try {
fis = new FileInputStream(myFile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Finds the workbook instance for XLSX file
XSSFWorkbook myWorkBook = null;
try {
myWorkBook = new XSSFWorkbook (fis);
} catch (IOException e) {
e.printStackTrace();
}
// Return first sheet from the XLSX workbook
XSSFSheet mySheet = myWorkBook.getSheetAt(0);
// Get iterator to all the rows in current sheet
Iterator<Row> rowIterator = mySheet.iterator();
// Traversing over each row of XLSX file
int count=1;
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
ArrayList<String> InnerArray = new ArrayList<String>() ;
if(debug)System.out.print(count + ". \t");
// 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_STRING:
String c = cell.getStringCellValue();
if(debug)System.out.print(c + "\t");
InnerArray.add(c);
break;
case Cell.CELL_TYPE_NUMERIC:
int n = (int) cell.getNumericCellValue();
if(debug)System.out.print(n + "\t");
InnerArray.add(String.valueOf(n));
break;
case Cell.CELL_TYPE_BOOLEAN:
boolean b = cell.getBooleanCellValue();
if(debug)System.out.print(b + "\t");
InnerArray.add(String.valueOf(b));
break;
default :
}
}
if(debug)System.out.println("");
OUT.add(InnerArray);
count++;
}
return OUT;
}
Look the code below
public List<ArrayList<String>> readExcelData2(String excelFile) throws IOException {
List<ArrayList<String>> depts = new ArrayList<ArrayList<String>>();
FileInputStream excelFileToRead = new FileInputStream(new File(excelFile));
XSSFWorkbook wb = new XSSFWorkbook(excelFileToRead);
XSSFSheet sheet = wb.getSheetAt(0);
XSSFRow row;
XSSFCell cell;
int maxDataCount = 0;
Iterator<Row> rows = sheet.rowIterator();
while (rows.hasNext()) {
row = (XSSFRow) rows.next();
// skip the first row because it will be header
if (row.getRowNum() == 0) {
maxDataCount = row.getLastCellNum();
continue;
}
// if the row is empty stop the loop, do not go further
if (this.isRowEmpty(row, maxDataCount)) {
// exit processing
break;
}
// define arraylist object to store list of departments of each row
ArrayList<String> innerArrayList = new ArrayList<String>();
for (int cn = 0; cn < maxDataCount; cn++) {
cell = row.getCell(cn, Row.CREATE_NULL_AS_BLANK);
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
innerArrayList.add(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_NUMERIC:
innerArrayList.add(String.valueOf(cell.getNumericCellValue()));
break;
default:
innerArrayList.add(cell.getStringCellValue());
break;
}
}
depts.add(innerArrayList);
}
return depts;
}
public boolean isRowEmpty(Row row, int lastCellNo) {
for (int c = row.getFirstCellNum(); c < lastCellNo; c++) {
Cell cell = row.getCell(c, Row.CREATE_NULL_AS_BLANK);
if (cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK) {
return false;
}
}
return true;
}
change your conditions part to this should be work :
if (cell.getCellType() == NUMERIC) {
System.out.print(cell.getNumericCellValue());
} else if (cell.getCellType() == STRING) {
System.out.print(cell.getRichStringCellValue());
} else if (cell.getCellType() == BOOLEAN) {
System.out.print(cell.getBooleanCellValue());
}