How to get the HSSFCell string value to List<String>> - java

I have created a method to pull the first row and another method to pull the test data. I am unable to add the cell directly to List using list.add(), how to convert them to string and add to list
public class read {
HSSFCell cell;
HSSFRow row;
HSSFWorkbook wbk;
HSSFSheet sheet;
List<HSSFCell> cellTempList;
Hashtable<String, String>[] data = null;
Iterator CIterator;
List<List<HSSFCell>> list;
HSSFFormulaEvaluator HFE = new HSSFFormulaEvaluator(wbk);
#SuppressWarnings("unchecked")
public String[] readFirstRow() throws IOException{
InputStream ipstream = new FileInputStream(new File("C:\readfile.xls"));
wbk = new HSSFWorkbook(ipstream);
sheet = wbk.getSheetAt(0);
row = sheet.getRow(0);
int numberofCells = row.getPhysicalNumberOfCells();
Object result;
String[] firstRow = new String[numberofCells];
for(int i = 0; i<= numberofCells; i++){
CIterator = row.cellIterator();
while(CIterator.hasNext()){
CIterator.next();
HSSFCell cellFirstRow = row.getCell(i);
switch(cellFirstRow.getCellType()){
case Cell.CELL_TYPE_BOOLEAN:
result = cell.getBooleanCellValue();
break;
case Cell.CELL_TYPE_NUMERIC:
result = cell.getNumericCellValue();
break;
case Cell.CELL_TYPE_STRING:
result = cell.getStringCellValue();
break;
}
for(int j=0; j<=numberofCells; j++){
firstRow[i] = result.toString();
}
}
return firstRow;
}
public void getNextRow(){
Object obj;
list = new ArrayList<List<HSSFCell>>();
cellTempList = new ArrayList<HSSFCell>();
HSSFRow rowNext = sheet.getRow(1);
Iterator rowIterator = sheet.rowIterator();
while (rowIterator.hasNext()) {
rowIterator.next();
CIterator = rowNext.cellIterator();
for(int j = 0; j<= rowNext.getPhysicalNumberOfCells();j++){
while (CIterator.hasNext()) {
CIterator.next();
//HSSFCell cell = rowNext.getCell(numberofCells);
cellTempList.add(cell);
}
list.add(cellTempList);
}
}
}

If your cell contains String value, you can get it with ..
String value = cell.getRichStringCellValue().getString();
.. and then add it to a List<String> object

Related

filter a column in excel to specific word using java code

I have an Excel file which needs filtering on a specific column.
String fileName = "filepath";
String cellContent = "Automation";
int rownr = 0;
int colnr = 0; //column from which you need data to store in array list
InputStream input = new FileInputStream(fileName);
XSSFWorkbook wb = new XSSFWorkbook(input);
XSSFSheet sheet = wb.getSheetAt(0);
List filteredCol = new ArrayList();
filteredCol = findRow(sheet, cellContent);
if (filteredCol != null) {
for (Iterator iter = filteredCol.iterator(); iter.hasNext(); ) {
System.out.println(iter.next());
}
}
private static List findRow(HSSFSheet sheet, String cellContent) {
List filter=new ArrayList();
for (Row row : sheet) {
for (Cell cell : row) {
if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
if (cell.getRichStringCellValue().getString().trim().equals(cellContent)) {
//System.out.println("Row numbers are"+row.getRowNum());
int rownumber=row.getRowNum();
//return row.getRowNum();
XSSFRow row1 = sheet.getRow(rownumber);
XSSFCell cell1 = row1.getCell(0);
filter.add(cell1);
}
}
}
}
return filter;
}
I am getting number format exception on this codeline:
"cell.getRichStringCellValue().getString().trim().equals(cellContent)"

reading values form excel with single row with multiple columns

How about reading the row with multiple values using excel
for instance
reference
testcase1
testcase2
testcase3
Name
Sam
ram
cam
Age
20
25
30
sex
m
F
m
place
place1
place2
place 3
I have to read
testcase1.name=sam
testcase2.name=ram
testcase3.name=cam
and age
how can I do this... any help would be appreciated
Use apache poi library.
First you must read the Excel file in a java object
FileInputStream myFile = new FileInputStream(new File(FILE_NAME));
Workbook myWorkbook = new XSSFWorkbook(myFile);
Sheet datatypeSheet = myWorkbook.getSheetAt(0); //read the first sheet
Iterator<Row> iterator = datatypeSheet.iterator();
Then you can iterate over each row and in each row you can read each cell (aka column value)
List<TestCase> myList = new ArrayList();
int rowNum = 0;
while (iterator.hasNext()) {
Row row = iterator.next();
int columnsSize = row.getLastCellNum();
//create all objects
if(rowNum == 0) {
for (int i = 1; i <= columnsSize; i++) {
myList.add(new TestCase());
}
} else {
//initialize property in each row for all objects
for (int i = 1; i <= columnsSize; i++) {
TestCase testCase = myList.get(i-1);
int cellType = row.getCell(i).getCellType();
switch(cellType) {
case Cell.CELL_TYPE_NUMERIC:
testCase.properties.add(new Property(row.getCell(0).getStringCellValue(),
String.valueOf(row.getCell(i).getNumericCellValue()));
break;
case Cell.CELL_TYPE_STRING:
testCase.properties.add(new Property(row.getCell(0).getStringCellValue(),
row.getCell(i).getStringCellValue());
break;
}
}
}
rowNum++;
}
System.out.println(myList);
public class TestCase {
public List<Property> properties;
public TestCase(){
this.properties = new ArrayList();
}
}
public class Property {
String name;
String value;
public Property(String name, String value){
this.name = name;
this.value = value;
}
}
*Edit: For loop must have <= condition instead of <
This tutorial might be helpful to use: https://www.javatpoint.com/how-to-read-excel-file-in-java.
Basically, you are using the Apache POI Library to parse the file's values, generating iterators for each row, then for each cell in each row, and dealing with the data that way.
In your case, after importing the relevant Classes, the code snippet will be something like this:
//Input Data for Class
FileInputStream in = new FileInputStream(new File("<File Location>.xls(x)"));
// Create an Apache POI Workbook reading the file
HSSFWorkbook workbook = new HSSFWorkbook(in);
// Use the Workbook to make a sheet
HSSFSheet sheet = workbook.getSheetAt(0); // Replace 0 with your sheet number
List<Row> rowsList = new ArrayList<Row>();
sheet.iterator().forEachRemaining(actualList::add); // Gets a list of all the rows
int i = -1;
String[] names = new String[3];
for (Cell cell : rowsList[1]) { // Start at second row
if (i++ > 0) {
names[i] = cell.getStringCellValue();
}
}
testcase1.name = names[0];
testcase2.name = names[1];
testcase3.name = names[2];
i = -1;
int[] ages = new int[3];
for (Cell cell : rowsList[2]) { // Start at Third Row
if (i++ > 0) {
ages[i] = (int) cell.getNumericCellValue();
}
}
testcase1.name = ages[0];
testcase2.name = ages[1];
testcase3.name = ages[2];

How to use excel column header as key in java using Apache-poi?

I want to use my column header of excel as key, so that I can print specific data column wise using that key. Below is my code in which I have used row as key, but could not do it column wise:
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheet("Bill");
Iterator<Row> rowIterator = sheet.iterator();
HashMap<Integer,List<String>> m= new HashMap<>();
int rownum=0;
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
List<String> lst=new LinkedList<String>();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
int a=(int) cell.getNumericCellValue();
lst.add(Integer.toString(a));
break;
case Cell.CELL_TYPE_STRING:
lst.add(cell.getStringCellValue());
break;
}
}
m.put(rownum,lst);
rownum++;
}
for (int i:m.keySet())
{
System.out.println(i+"-----"+m.get(i));
}
read the excel like code below. put the first column into the map with key "columns" after reading excel, fetch the column list with
List columns = (List) dataList.get(0).get("columns");
public List<HashMap<String, Object>> readExcel(InputStream inputStream, String dateFormat) {
ArrayList<HashMap<String, Object>> result = new ArrayList<HashMap<String, Object>>();
try {
XSSFWorkbook workbook;
workbook = new XSSFWorkbook(inputStream);
XSSFSheet spreadsheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = spreadsheet.iterator();
int c = 0;
ArrayList<String> columns = new ArrayList<String>();
while (rowIterator.hasNext()) {
row = (XSSFRow) rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
HashMap<String, Object> map = new HashMap<String, Object>();
if (c == 0) {
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
if (cell.getStringCellValue().trim() != null && !cell.getStringCellValue().trim().equals("")) {
columns.add(cell.getStringCellValue().trim());
}
}
} else {
for (int i = 0; i < columns.size(); i++) {
Cell cell = row.getCell(i);
if (cell != null) {
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellInternalDateFormatted(cell)) {
DateFormat df = new SimpleDateFormat(dateFormat);
map.put(columns.get(i), df.format(cell.getDateCellValue()));
break;
} else {
map.put(columns.get(i), cell.getNumericCellValue());
break;
}
case Cell.CELL_TYPE_STRING:
map.put(columns.get(i), cell.getStringCellValue().trim());
break;
}
} else {
map.put(columns.get(i), "");
}
}
}
if (c == 0) {
map.put("columns", columns);
}
c++;
if (!isEmptyRow(map)) {
map.put("rowNumber", c);
result.add(map);
}
}
inputStream.close();
return result;
} catch (IOException e) {
e.printStackTrace();
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}

Passing a list of servlet values

Using apache poi, I am reading the first row values of an excel file like this
try
{
FileInputStream file = new FileInputStream(uploadedFile);
XSSFWorkbook workbook = new XSSFWorkbook(file);
for (int i =0; i < workbook.getNumberOfSheets(); i++)
{
XSSFSheet sheet = workbook.getSheetAt(i);
Iterator<Row> rowIterator = sheet.iterator();
String SheetName = "<span class='blue'><b>" +sheet.getSheetName()+ "<b></span><br>";
request.setAttribute("SheetName", SheetName);
Row row = rowIterator.next();
if(row.getRowNum() == 0)
{
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext())
{
Cell cell1 = cellIterator.next();
switch(cell1.getCellType())
{
case Cell.CELL_TYPE_STRING:
String strval = cell1.getStringCellValue();
request.setAttribute("Values2", strval);
break;
}
}
}
}
file.close();
}catch(NoSuchElementException e)
{}
Now, I want to pass a list of values the strval is only sending one value, how do I sent many values??
How to send an array of items to my jsp page?
You can send List as an attribute value. For example:
List<String> cellValues = new ArrayList<String>();
while(cellIterator.hasNext())
{
Cell cell1 = cellIterator.next();
switch(cell1.getCellType())
{
case Cell.CELL_TYPE_STRING:
String strval = cell1.getStringCellValue();
cellValues.add(strval);
break;
}
}
}
}
request.settAttribute("Values2", cellValues);

Request for resolving the error cannot convert from void to HSSFCell

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

Categories