Print the value of 10 and 11 column from excel using java - java

I have code to print all the values of excel cells but it's ignoring the blank cells. Is there any way to print the value of blank cell (null) as well?
And also is it possible to print particular 2 specific columns (with blank cells) like 10th and 11th column?
Below is my code. Please suggest what can i change in below code?
package excel;
import java.io.File;
import java.io.FileInputStream;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class Excel
{
public static void main(String[] args) {
try {
FileInputStream file = new FileInputStream(new File("C:\\Users\\gur29175\\Desktop\\1.xlsx"));
//Create Workbook instance holding reference to .xlsx file
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(0);
//Iterate through each rows one by one
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext())
{
Row row = rowIterator.next();
//For each row, iterate through all the columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext())
{
Cell cell = cellIterator.next();
//Check the cell type and format accordingly
System.out.print(cell.getStringCellValue() + "\t");
}
System.out.println("");
}
file.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

Row row = rowIterator.next();
for(int i = 0; i < row.getLastCellNum(); i++) {
Cell cell = row.getCell(i);
if(cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK) {
// handle not null values
}else{
// handle null values
}
}

Related

How to write specific row when condition is met in another Excel sheet [duplicate]

This question already has answers here:
How do I resolve ClassNotFoundException?
(28 answers)
Closed 6 months ago.
I am in a learning stage of Java. I want to write a program in Java which reads one Excel file (.xlsx). This file has some columns and many rows. I want to write the data in another Excel file (.xlsx) only the condition is met not all the data from existing file.
My Excel sheet looks like below
I want to filter only those rows with broker Edelweiss and put it in another Excel sheet. I am aware how to copy all the data from one Excel to another Excel using Java. I don't know how to filter a specific row and put it in another Excel.
Here is my code.
FileInputStream file = new FileInputStream(new File("broker.xlsx"));
//Create Workbook instance holding reference to .xlsx file
XSSFWorkbook workbook = new XSSFWorkbook(file);
//Get first/desired sheet from the workbook
XSSFSheet sheet = workbook.getSheetAt(0);
//Iterate through each rows one by one
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext())
{
Row row = rowIterator.next();
//For each row, iterate through all the columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext())
{
Cell cell = cellIterator.next();
//Check the cell type and format accordingly
switch (cell.getCellType())
{
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "t");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "t");
break;
}
}
System.out.println("");
}
file.close();
}
catch (Exception e)
{
e.printStackTrace();
}
I am getting the below error when I run Axel Richter's code which is shared below
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/io/output/UnsynchronizedByteArrayOutputStream
at org.apache.poi.poifs.filesystem.FileMagic.valueOf(FileMagic.java:209)
at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:222)
at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:185)
at writefile.main(writefile.java:92)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream
at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:355)
at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
I have included below jars in my classpath
POI_LIB=$(TOP_DIR)/jar/poi-bin-5.2.2/poi-5.2.2.jar
POI_OOXML_LIB=$(TOP_DIR)/jar/poi-bin-5.2.2/poi-ooxml-full-5.2.2.jar
XML_BEANS_LIB=$(TOP_DIR)/jar/poi-bin-5.2.2/ooxml-lib/xmlbeans-5.0.3.jar
COM_COLL_LIB=$(TOP_DIR)/jar/poi-bin-5.2.2/lib/commons-collections4-4.4.jar
COM_COMPRESS_LIB=$(TOP_DIR)/jar/poi-bin-5.2.2/ooxml-lib/commons-compress-1.21.jar
COM_CODEC_LIB=$(TOP_DIR)/jar/poi-bin-5.2.2/lib/commons-codec-1.15.jar
COM_IO_LIB=$(TOP_DIR)/jar/poi-bin-5.2.2/lib/commons-io-2.11.0.jar
COM_MATH_LIB=$(TOP_DIR)/jar/poi-bin-5.2.2/lib/commons-math3-3.6.1.jar
LOG_J4_LIB=$(TOP_DIR)/jar/poi-bin-5.2.2/lib/log4j-api-2.17.2.jar
SPARSE_LIB=$(TOP_DIR)/jar/poi-bin-5.2.2/lib/SparseBitSet-1.2.jar
COM_LOGG_LIB=$(TOP_DIR)/jar/poi-bin-5.2.2/ooxml-lib/commons-logging-1.2.jar
CURVE_LIB=$(TOP_DIR)/jar/poi-bin-5.2.2/ooxml-lib/curvesapi-1.07.jar
SLF4_LIB=$(TOP_DIR)/jar/poi-bin-5.2.2/ooxml-lib/slf4j-api-1.7.36.jar
I will make my comment an answer.
I would open the source sheet and loop through all rows in it. For each row I would get the content of the column where "Broker" is stored. Then, if that content equals "Edelweiss" I would get that row into a Java collection, a list of rows for example. After that I would write the content of that Java collection into the result sheet.
The following complete example shows this.
It contains methods to get the last filled row in a special column of a sheet and to get the last filled column in a special row of a sheet. That is to determine the used cell range of a sheet.
It also contains a method to get the headings, which maps headings to column indexes. The headings must be in first row of the used cell range of the sheet.
It also shows how to use CellUtil.copyCell to copy cells from one sheet to another.
The code is tested and works using current apache poi 5.2.2.
The first sheet of broker.xlsx looks like:
Code:
import java.io.FileOutputStream;
import java.io.FileInputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellUtil;
import java.util.Locale;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
class ExcelFilterRowsToNewWorkbook {
static int getLastFilledRow(Sheet sheet, int col) {
int lastStoredRowNum = sheet.getLastRowNum();
for (int r = lastStoredRowNum; r >= 0; r--) {
Row row = sheet.getRow(r);
if (row != null) {
Cell cell = row.getCell(col);
if (cell != null && cell.getCellType() != CellType.BLANK) return row.getRowNum();
}
}
return -1; // the sheet is empty in that col
}
static int getLastFilledColumn(Sheet sheet, int rowIdx) {
int lastStoredCellNum = sheet.getRow(rowIdx).getLastCellNum();
Row row = sheet.getRow(rowIdx);
if (row != null) {
for (int c = lastStoredCellNum; c >= 0; c--) {
Cell cell = row.getCell(c);
if (cell != null && cell.getCellType() != CellType.BLANK) return cell.getColumnIndex();
}
}
return -1; // the sheet is empty in that row
}
static Map<Integer, String> getHeadings(Sheet sheet) {
DataFormatter dataFormatter = new DataFormatter(new Locale("en", "US"));
dataFormatter.setUseCachedValuesForFormulaCells(true);
int firstRow = sheet.getFirstRowNum();
int firstCol = sheet.getRow(firstRow).getFirstCellNum();
int lastCol = getLastFilledColumn(sheet, firstRow);
Map<Integer, String> headings = new HashMap<Integer, String>();
Row row = sheet.getRow(firstRow);
if (row != null) {
for (int c = firstCol; c <= lastCol; c++) {
Cell cell = row.getCell(c);
headings.put(c, dataFormatter.formatCellValue(cell));
}
}
return headings;
}
static List<Row> filterRows(Sheet sheet, String filterHeading, String filterValue) {
int filterCol = -1;
Map<Integer, String> headings = getHeadings(sheet);
for (Map.Entry<Integer, String> entry : headings.entrySet()) {
if (entry.getValue().equals(filterHeading)) {
filterCol = entry.getKey();
break;
}
}
List<Row> rows = new ArrayList<Row>();
// add the headings row
int firstRow = sheet.getFirstRowNum();
rows.add(sheet.getRow(firstRow));
// add the fildered rows
if (filterCol > -1) {
DataFormatter dataFormatter = new DataFormatter(new Locale("en", "US"));
dataFormatter.setUseCachedValuesForFormulaCells(true);
int firstCol = sheet.getRow(firstRow).getFirstCellNum();
int lastCol = getLastFilledColumn(sheet, firstRow);
int lastRow = getLastFilledRow(sheet, firstCol);
for (int r = firstRow; r <= lastRow; r++) {
Row row = sheet.getRow(r);
if (row != null && lastCol >= filterCol) {
Cell cell = row.getCell(filterCol);
String cellContent = dataFormatter.formatCellValue(cell);
if (cellContent.equals(filterValue)) {
rows.add(row);
}
}
}
}
return rows;
}
public static void main(String[] args) throws Exception {
try (Workbook workbookSrc = WorkbookFactory.create(new FileInputStream("./broker.xlsx")) ) {
Sheet sheetSrc = workbookSrc.getSheetAt(0);
// get filtered rows
List<Row> rowsSrc = filterRows(sheetSrc, "Broker", "Edelweiss");
// add filtered rows in new workbook
try (Workbook workbookDest = WorkbookFactory.create(true);
FileOutputStream fileout = new FileOutputStream("./brokerFiltered.xlsx") ) {
Sheet sheetDest = workbookDest.createSheet();
int r = 0;
for (Row rowSrc : rowsSrc) {
Row rowDest = sheetDest.createRow(r++);
for (Cell cellSrc : rowSrc) {
Cell cellDest = rowDest.createCell(cellSrc.getColumnIndex());
CellUtil.copyCell(cellSrc,
cellDest,
new CellCopyPolicy(),
new CellCopyContext()
);
}
}
workbookDest.write(fileout);
}
}
}
}
The first sheet of brokerFiltered.xlsx then looks like:

Read the Adjacent cell value in Excel Sheet using Java

I have an excel sheet and I want to give it a string input and have the java code look for the input in the excel sheet. And when it finds it, it prints the adjacent cell (the one on its right).
This code just gives me all the excel sheet values. But what I want is for it to give me a specific value.
This is my code:
package readfiles;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
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;
public class LeerArchivosDeExcel {
public LeerArchivosDeExcel(File fileName){
List cellData = new ArrayList();
try {
FileInputStream fileInputStream = new FileInputStream(fileName);
XSSFWorkbook workBook = new XSSFWorkbook(fileInputStream);
XSSFSheet hssfSheet = workBook.getSheetAt(0);
Iterator rowIterator = hssfSheet.rowIterator();
while(rowIterator.hasNext()){
XSSFRow hssfRow = (XSSFRow) rowIterator.next();
Iterator iterator = hssfRow.cellIterator();
List cellTemp = new ArrayList();
while (iterator.hasNext()){
XSSFCell hssfCell = (XSSFCell) iterator.next();
cellTemp.add(hssfCell);
}
cellData.add(cellTemp);
}
} catch (Exception e) {
e.printStackTrace();
}
obtener(cellData);
}
private void obtener(List cellDataList){
for (int i = 0; i < cellDataList.size(); i++) {
List cellTempList = (List) cellDataList.get(i);
for (int j = 0; j < cellTempList.size(); j++) {
XSSFCell hssfCell = (XSSFCell) cellTempList.get(j);
String stringCellValue = hssfCell.toString();
System.out.print(stringCellValue+" ");
}
System.out.println();
}
}
public static void main(String[] args) {
File f = new File ("/Users/sushi/Documentos/BD2/Libro.xlsx");
Scanner input = new Scanner(System.in);
if (f.exists()){
LeerArchivosDeExcel obj = new LeerArchivosDeExcel(f);
}
}
}
You can write a method like this:
public String getAdjacentCellValue(Sheet sheet, String searchText) {
DataFormatter formatter = new DataFormatter();
for (Row row : sheet) {
for (Cell cell : row) {
if (searchText.equals(formatter.formatCellValue(cell))) {
// text matches the string cell value,
// so find the adjacent cell
Cell adjacentCell = row.getCell(cell.getColumnIndex() + 1);
if (adjacentCell == null) {
// cell does not exist in excel model yet,
// so it is considered a blank cell by default
return "";
} else {
// cell exists in excel model
// return the value
return formatter.formatCellValue(adjacentCell);
}
}
}
}
// search text not found
return null;
}
Some notes are appropriate here:
You can iterate the worksheet this succinctly because the Sheet interface extends Iterable<Row> and the Row interface extends Iterable<Cell>.
Use DataFormatter to read a cell's string value becausecell.getStringCellValue() will not work if the cell type is NUMERIC, for example. Additional configuration will be necessary if the cell is a formula cell.
The method invocation row.getCell(cell.getColumnIndex() + 1) may return null. Internally, Excel assumes that all cells in a sheet are blank cells unless otherwise specified. It only stores cells that have been explicitly edited. If the cell has never been created POI returns null. This is not unusual for a typical worksheet.

How to access excel cell using cell name with java [duplicate]

I am writing a Java program to read data from excel sheet (having XLSX extension) using Apache POI library. I am able to iterate through all the cells and get all the values. But I am unable to get a specific cell value, say E10.
Is there any way to do this?
Please see the code below that I used for iterating through the cells.
package application;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
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.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ReadFromXLSX {
public static void readXLSXFile() throws IOException
{
InputStream ExcelFileToRead = new FileInputStream("C:\\Test.xlsx");
XSSFWorkbook wb = new XSSFWorkbook(ExcelFileToRead);
XSSFWorkbook test = new XSSFWorkbook();
XSSFSheet sheet = wb.getSheetAt(0);
XSSFRow row;
XSSFCell cell;
Iterator rows = sheet.rowIterator();
while (rows.hasNext())
{
row=(XSSFRow) rows.next();
Iterator cells = row.cellIterator();
while (cells.hasNext())
{
cell=(XSSFCell) cells.next();
if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING)
{
System.out.print(cell.getStringCellValue()+" ");
}
else if(cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC)
{
System.out.print(cell.getNumericCellValue()+" ");
}
else
{
}
}
System.out.println();
}
}
}
For example, to get E10 of the first worksheet:
wb.getSheetAt(0).getRow(9).getCell(4);
Note: subtract one because the indices are null-based.
You can also use this convenience method to map E to 4.
wb.getSheetAt(0).getRow(9).getCell(CellReference.convertColStringToIndex("E"));
To get a value from a specific cell in excel you can use the below code line.
wb.getSheetAt(0).getRow(1).getCell(1);
XSSFSheet has the method getRow(int rownum)
It returns the logical row ( 0-based). If you ask for a row that is not defined you get a null. This is to say row 4 represents the fifth row on a sheet.
Once you get the row, you can call getCell(int cellnum) method of XSSFRow object. It returns the cell at the given (0 based) index.
Just version-up the getCell method
public XSSFCell getCell(String cellName){
Pattern r = Pattern.compile("^([A-Z]+)([0-9]+)$");
Matcher m = r.matcher(cellName);
XSSFWorkbook wb = new XSSFWorkbook();
if(m.matches()) {
String columnName = m.group(1);
int rowNumber = Integer.parseInt(m.group(2));
if(rowNumber > 0) {
return wb.getSheetAt(0).getRow(rowNumber-1).getCell(CellReference.convertColStringToIndex(columnName));
}
}
return null;
}
Now you can get the cell easily by this line
getCell("E10")
public class XmlFileRead {
public static void main(String[] args) throws IOException {
FileInputStream fi = new FileInputStream("abc.xls");
ArrayList<EmployeeVo> al = new ArrayList<>();
EmployeeVo evo = null;
Scanner scanner = null;
Workbook wb = new XSSFWorkbook(fi);
Sheet sh = wb.getSheet("Sheet0");
int starRow = sh.getFirstRowNum();
int endRow = sh.getLastRowNum();
for (int i = starRow + 1; i < endRow; i++) {
scanner = new Scanner(System.in);
evo = new EmployeeVo();
Cell c = wb.getSheetAt(0).getRow(i).getCell(1);
evo.setEmployeeId((int) c.getNumericCellValue());
Cell c2 = wb.getSheetAt(0).getRow(i).getCell(2);
evo.setEmployeeName(c2.toString());
// add to collection
al.add(evo);
} // for
al.forEach(i -> {
System.out.println(i.getEmployeeId() + " " + i.getEmployeeName());
});
}
}

Getting data from Excel and print count of rows into Excel using JAVA

S_No Operators About No.Of-Busses Main-Routes No.Of-Routes Popular-Routes
1 A-G-Holidays *** 10 Delhi - Haridwar Delhi - Haridwar
Delhi - Dehradun
Delhi - Kanpur
Delhi - Lucknow
Delhi - Rishikesh
Rishikesh - Delhi
Kanpur - Lucknow
Haridwar - Delhi
Haridwar - Rishikesh
Haridwar - Dehradun
blank line-----------------------------------------------------------------------
2 A-K-Travels *** 2 0
Mumbai - Indore
Indore - Mumbai
Hi, I Have a Excel Sheet like above. I need to count all popular routes and print that count in No.of-Routes column on corresponding S_No row. Also I have an blank line after every S_No's. And these all popular routes are not placed in one cell(each route is one row).
I tried with below code. I'm not able to move forward,please help me.
public class PrintNoOfRoutes
{
public static void main(String args[]) throws Exception
{
List list=new ArrayList();
FileInputStream file = new FileInputStream(new File("D:/BusOperators/sample.xlsx"));
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
rowIterator.next();
Row row = rowIterator.next();
int S_No=(int) row.getCell(0).getNumericCellValue();
System.out.println(S_No);
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext())
{
Cell cell = cellIterator.next();
switch(cell.getCellType())
{
case Cell.CELL_TYPE_BOOLEAN:
System.out.println("boolean===>>>"+cell.getBooleanCellValue() + "\t");
break;
case Cell.CELL_TYPE_NUMERIC:
int S_No=(int) row.getCell(0).getNumericCellValue();
System.out.println(S_No);
break;
case Cell.CELL_TYPE_STRING:
//list.add(cell.getStringCellValue());
if(c==S_No)
{
System.out.println("done");
row.getCell(6);
Row row2 = rowIterator.next();
if(cell.getStringCellValue() != null)
{
count=1;
System.out.println(count);
count++;
}
break;
}
This worked for me. This depends on a blank line to indicate when to stop counting popular routes for a particular S_No. S_No and No.Of-Routes must be numeric fields.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
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;
public class PrintNoOfRoutes
{
private static final String INFILE_NAME = "C:\\sample.xlsx";
private static final String OUTFILE_NAME = "C:\\sampleout.xlsx";
public static void main(String[] args) {
try {
FileInputStream excelFile = new FileInputStream(new File(INFILE_NAME));
Workbook workbook = new XSSFWorkbook(excelFile);
Sheet datatypeSheet = workbook.getSheetAt(0);
Iterator<Row> iterator = datatypeSheet.iterator();
boolean firstTime = true;
int numRoutes = 0;
Cell routeCell = null;
while (iterator.hasNext()) {
Row currentRow = iterator.next();
Iterator<Cell> cellIterator = currentRow.iterator();
while (cellIterator.hasNext()) {
Cell currentCell = cellIterator.next();
if (currentCell.getCellTypeEnum() == CellType.STRING && currentCell.getColumnIndex() == 6) {
//found a route to count
String val = currentCell.getStringCellValue();
if (!firstTime) //don't count header row
numRoutes++;
} else if (currentCell.getCellTypeEnum() == CellType.NUMERIC && currentCell.getColumnIndex() == 0) {
//found an S_No cell with a value
if (!firstTime) {
//set the number of routes for the previous S_No
routeCell.setCellValue(numRoutes);
numRoutes = 0; //reset
} else {
firstTime = false;
}
routeCell = currentRow.getCell(5); //save the No.Of-Routes cell for this S_No
}
}
}
//write last route count
routeCell.setCellValue(numRoutes);
//write out the workbook
File outfile = new File(OUTFILE_NAME);
FileOutputStream fos = new FileOutputStream(outfile);
workbook.write(fos);
workbook.close();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Count number of rows in a column of Excel sheet(Java code provided)

In reference to my previous question How to calculate number of rows in a column of Excel document using Java i was able to calculate the total number of columns in the given sheet. Now half of the work is yet to be done as i want to calculate the number of rows in a particular column. Possible solution could be using 2d array and storing column index and the total rows or using map, etc. How i can achieve this? Java code is provided here. I'm getting right count(column count) for my demo file. Please modify/suggest changes as required.
(edit): i've used hasp map to calculate store column index as key and row count as value, but it wasnt working, may be the applied logic was wrong. Well, if i want to accomplish this by using Hash Map, how i can store number of rows in a particular column(while iterating) as a value
Java Code:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import org.apache.poi.ss.formula.functions.Column;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelRead {
static int colrange=1000;
public static void main(String[] args) {
HashMap hm=new HashMap();
int count=0;
try {
FileInputStream file = new FileInputStream(new File("C:/Users/vinayakp/Desktop/Demo2.xlsx"));
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
while(rowIterator.hasNext()) {
Row row = rowIterator.next();
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("");
}
for(Row r:sheet)
{
short minColIx=r.getFirstCellNum();
short maxColIx=r.getLastCellNum();
for(short colIx=minColIx;colIx<maxColIx;colIx++) {
Cell c= r.getCell(colIx);
if(c!=null) {
if(c.getCellType()== Cell.CELL_TYPE_STRING||c.getCellType() == Cell.CELL_TYPE_NUMERIC||c.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
count++; ---// can i use hashcode in here to get the key and value pair? key=column index value=total number of rows in that column
}
}
else break;
}
}
System.out.println("\nTotal Number of columns are:\t"+count);
System.out.println(hm);
file.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException ae) {
ae.printStackTrace();
}
}
}
Try this:
private void excelReader() {
String data;
try {
InputStream is = new FileInputStream("Read.xlsx");
Workbook wb = WorkbookFactory.create(is);
Sheet sheet = wb.getSheetAt(0);
Iterator rowIter = sheet.rowIterator();
Row r = (Row)rowIter.next();
short lastCellNum = r.getLastCellNum();
int[] dataCount = new int[lastCellNum];
int col = 0;
rowIter = sheet.rowIterator();
while(rowIter.hasNext()) {
Iterator cellIter = ((Row)rowIter.next()).cellIterator();
while(cellIter.hasNext()) {
Cell cell = (Cell)cellIter.next();
col = cell.getColumnIndex();
dataCount[col] += 1;
DataFormatter df = new DataFormatter();
data = df.formatCellValue(cell);
System.out.println("Data: " + data);
}
}
is.close();
for(int x = 0; x < dataCount.length; x++) {
System.out.println("col " + x + ": " + dataCount[x]);
}
}
catch(Exception e) {
e.printStackTrace();
return;
}
}
Tested code
I created an xlsx file with the following cell data:
Col0 Col1 Col2 Col3 Col4
1 a x a q
2 b y s w
3 c z d e
4 d f r
5 e t
y
The contents of dataCount array is this:
col 0: 6
col 1: 6
col 2: 4
col 3: 5
col 4: 7
The numbers on the right count the number of cells with data for each column, including the header row.
If you want to exclude the header row, just remove the line:
rowIter = sheet.rowIterator();
just before the while loop.
Is this what you are looking for?
Will this solve?
HSSFSheet mySheet = myWorkBook.getSheetAt(0);
Iterator<Row> rowIter = mySheet.rowIterator();
while (rowIter.hasNext()) {
HSSFRow myRow = (HSSFRow) rowIter.next();
Iterator<Cell> cellIter = myRow.cellIterator();
List<HSSFCell> cellStore = new ArrayList<HSSFCell>();
while (cellIter.hasNext()) {
HSSFCell myCell = (HSSFCell) cellIter.next();
rowCount++ //For myRow
}
}
it is giving the total number of data in the excel sheet, i mean including the header column name as well.
In my understanding, you want to count the number of rows that a column has, EXCEPT for the header row.
If that's the case, you can use the solution provided by Binu. Just modify it to skip the row where the column name is.

Categories

Resources