Set new cell value by cell name in Apache POI - java

I'm new to Java and Apache POI, but I got this task where I have to read from the command line the name of the Excel file and the name and values of the columns that needs to be modified.
So in the end the application will run like this:
java test -f test.xls -i B2=10;B3=20;B4=30
I have created a map that holds the cell name and their values, but I don't know how to use this map in order to access cells by their name (eg.: B2) and set the new value (eg.: 10).
My code so far is bellow:
package test;
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 java.util.Map;
import java.util.Map.Entry;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator;
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.hssf.util.CellReference;
import org.apache.poi.ss.usermodel.*;
public class ReadExcel {
public static void main(String[] args) throws FileNotFoundException, IOException {
// Will contain cell name / value pair for input cells and output cells
Map<String, String> inputCellsMap = new HashMap<String, String>();
Map<String, String> outputCellsMap = new HashMap<String, String>();
// Open the Excel file
FileInputStream file = new FileInputStream(new File(args[1]));
// Get the current workbook
HSSFWorkbook workbook = new HSSFWorkbook(file);
// Get the first sheet of the workbook
HSSFSheet sheet = workbook.getSheetAt(0);
// Get the input cells that need to be modified and
// store their name and value in the inputCellsMap
for (String element : args[3].split(";")) {
inputCellsMap.put(element.split("=")[0], element.split("=")[1]);
}
// Loop through the cells that need to be modified and
// set the new value in the Excel document
Iterator<Entry<String,String>> iterator = inputCellsMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String,String> entry = (Map.Entry<String,String>) iterator.next();
// TODO
// Get cells by name and set their new value
//System.out.println("Key : " + entry.getKey() + " Value :" + entry.getValue());
}
workbook.close();
}
}

Once you have the entry, get the cell reference text, e.g. "B2", and the value.
Create a CellReference using the text. Then you can obtain the 0-based row and column indexes that you can use to get the Row and then the Cell object, on which you can call setCellValue.
CellReference cr = new CellReference(entry.getKey());
int r = cr.getRow();
int c = cr.getCol();
Row row = sheet.getRow(r);
if (row == null)
row = sheet.createRow(r);
Cell cell = row.getCell(c, Row.CREATE_NULL_AS_BLANK);
cell.setCellValue(entry.getValue());

You can access a row and column using these methods. (eg. E101)
sheet.getRow(100).getCell(5)

Related

Check if a cell has a data validation of type list behind it in APACHE POI [duplicate]

I'm trying to get the pre-existing data validation information out of an Excel cell with Apache POI. For example, if a cell already has a data validation constraint that only allows integers between 0 and 100, I'd like to be able to pull that information out of the cell.
On the Data Validation section of the Quick Guide, the examples only seem to cover adding validation to cells, not retrieving it. I've found the DataValidationEvaluator object that appears to do what I am looking for with its getValidationForCell method. However, I cannot figure out how to properly instantiate an instance of this object since its constructor requires a WorkbookEvaluatorProvider which, according to its official documentation, is for internal POI use only.
Any help or guidance on this would be greatly appreciated! Maybe one of you will know a much easier and better way to get this information. Here is a snippet of code that demonstrates what I would like to do:
// The impossible (?) bit
WorkbookEvaluatorProvider wep = ...???...
// Easy through here
DataValidationEvaluator dve = new DataValidationEvaluator(wb, wep)
CellReference cRef = aRef.getFirstCell();
DataValidation dv = dve.getValidationForCell(cRef);
We can have a method which gets the data validation constraint out of the given Cell.
First we need get sheet's data validations and then for each data validation get Excel cell ranges the data validation applies to. If the cell is in one of that cell ranges then return that validation constraint.
Example:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import java.io.FileInputStream;
import java.util.List;
import java.util.Arrays;
public class ExcelGetDataValidationConstraints {
static DataValidationConstraint getDataValidationConstraint(Cell cell) {
Sheet sheet = cell.getSheet();
List<? extends DataValidation> dataValidations = sheet.getDataValidations(); // get sheet's data validations
for (DataValidation dataValidation : dataValidations) {
CellRangeAddressList addressList = dataValidation.getRegions(); // get Excel cell ranges the data validation applies to
CellRangeAddress[] addresses = addressList.getCellRangeAddresses();
for (CellRangeAddress address : addresses) {
if (address.isInRange(cell)) { // if the cell is in that cell range
DataValidationConstraint constraint = dataValidation.getValidationConstraint();
return constraint; // return this
}
}
}
return null; // per default return null
}
public static void main(String[] args) throws Exception {
//String filePath = "ExcelWorkbook.xls";
String filePath = "ExcelWorkbook.xlsx";
Workbook workbook = WorkbookFactory.create(new FileInputStream(filePath));
Sheet sheet = workbook.getSheetAt(0);
for (Row row : sheet) {
for (Cell cell : row) {
DataValidationConstraint constraint = getDataValidationConstraint(cell);
System.out.println(cell.getAddress());
System.out.println(constraint);
if (constraint != null) {
System.out.println("DataValidationConstraint.ValidationType: " + constraint.getValidationType());
//https://poi.apache.org/apidocs/dev/org/apache/poi/ss/usermodel/DataValidationConstraint.ValidationType.html
System.out.println("Formula1: " + constraint.getFormula1());
System.out.println("DataValidationConstraint.OperatorType: " + constraint.getOperator());
//https://poi.apache.org/apidocs/dev/org/apache/poi/ss/usermodel/DataValidationConstraint.OperatorType.html
System.out.println("Formula2: " + constraint.getFormula2());
String[] listValues = constraint.getExplicitListValues();
if (listValues != null) System.out.println("List values: " + Arrays.asList(listValues));
}
System.out.println();
}
}
workbook.close();
}
}
See How to get datavalidation source for a cell in java using poi? for working with differnt types of list constraints.
To answer your question about using WorkbookEvaluatorProvider:
WorkbookEvaluatorProvider is an interface which is implemented by all FormulaElevators. So to get a WorkbookEvaluatorProvider we need creating a FormulaEvaluator. This can be done using CreationHelper.html#createFormulaEvaluator. The CreationHelper can be got form the Workbook.
So what you have described could be done using method:
DataValidation getDataValidationFromDataValidationEvaluator (Cell cell) {
Sheet sheet = cell.getSheet();
Workbook workbook = sheet.getWorkbook();
WorkbookEvaluatorProvider workbookEvaluatorProvider =
(WorkbookEvaluatorProvider)workbook.getCreationHelper().createFormulaEvaluator();
DataValidationEvaluator dataValidationEvaluator = new DataValidationEvaluator(workbook, workbookEvaluatorProvider);
DataValidation dataValidation = dataValidationEvaluator.getValidationForCell(new CellReference(cell));
return dataValidation;
}
Complete example:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;
import org.apache.poi.ss.formula.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import java.io.FileInputStream;
import java.util.List;
import java.util.Arrays;
public class ExcelGetDataValidationFromDataValidationEvaluator {
static DataValidation getDataValidationFromDataValidationEvaluator (Cell cell) {
Sheet sheet = cell.getSheet();
Workbook workbook = sheet.getWorkbook();
WorkbookEvaluatorProvider workbookEvaluatorProvider =
(WorkbookEvaluatorProvider)workbook.getCreationHelper().createFormulaEvaluator();
DataValidationEvaluator dataValidationEvaluator = new DataValidationEvaluator(workbook, workbookEvaluatorProvider);
DataValidation dataValidation = dataValidationEvaluator.getValidationForCell(new CellReference(cell));
return dataValidation;
}
public static void main(String[] args) throws Exception {
//String filePath = "ExcelWorkbook.xls";
String filePath = "ExcelWorkbook.xlsx";
Workbook workbook = WorkbookFactory.create(new FileInputStream(filePath));
Sheet sheet = workbook.getSheetAt(0);
for (Row row : sheet) {
for (Cell cell : row) {
System.out.println(cell.getAddress());
DataValidation dataValidation = getDataValidationFromDataValidationEvaluator(cell);
if (dataValidation!=null) {
DataValidationConstraint constraint = dataValidation.getValidationConstraint();
System.out.println(dataValidation);
System.out.println(constraint);
if (constraint != null) {
System.out.println("DataValidationConstraint.ValidationType: " + constraint.getValidationType());
//https://poi.apache.org/apidocs/dev/org/apache/poi/ss/usermodel/DataValidationConstraint.ValidationType.html
System.out.println("Formula1: " + constraint.getFormula1());
System.out.println("DataValidationConstraint.OperatorType: " + constraint.getOperator());
//https://poi.apache.org/apidocs/dev/org/apache/poi/ss/usermodel/DataValidationConstraint.OperatorType.html
System.out.println("Formula2: " + constraint.getFormula2());
String[] listValues = constraint.getExplicitListValues();
if (listValues != null) System.out.println("List values: " + Arrays.asList(listValues));
}
}
System.out.println();
}
}
workbook.close();
}
}
Worth testing what approach is more performant.

How to read .xlsx file with apache poi?

See the picture below, I am trying to write a program that can "scan" a given row with no limit of from which cell to which cell, then, find all the "strings" that are identical the same. Is it possible to do that? Thank you.
To give an example so that this will not be very confusing, for ex.: On row H, you see there are customer's names, there are "Coresystem", "Huawei", "VIVO", etc... Now the problem is, what if the names are not grouped together, they are all split up, like, On H5, it will be "Huawei" and On H9, it will be "VIVO", etc, it's like, unlike the picture provided below, on row H all the names are split up, and I want apache POI to find all the customers that have the same name, for ex.: If user enter "coReSysteM", it should be able to find all the .equalsIgnoreCase of all Coresystem on row H (btw, the user should be able to enter the customer's name that they want to enter and the row they want to search for), and display from A5, B5, C5, D5, E5, F5, G5, H5 to A14, B14, C14, D14, E14, F14, G14, H5, is it possible?
I was thinking about setting a formula to find all the customer, for example: =CountIf
These are the code that I am currently trying to do, but then I am stuck with it:
package excel_reader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
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 ExcelReader2d {
ExcelReader link = new ExcelReader();
Scanner scan = new Scanner(System.in);
// instance data
private static int numberGrid[][] = null;
private static String stringGrid[][] = null;
// constructor
public ExcelReader2d(String desLink) {
}
// methods
public void ExeScan() throws FileNotFoundException, IOException {
Scanner scan = new Scanner(System.in);
XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream("C:\\Users\\Sonic\\Desktop\\20191223 IMPORTS.xlsx"));
XSSFSheet sheet = workbook.getSheetAt(0);
final int rowStart = Math.min(15, sheet.getFirstRowNum()), rowEnd = Math.max(1400, sheet.getLastRowNum());
System.out.print("Enter the rows that you want to search for: (for ex. the rows that stores customer's name) ");
int searchRows = scan.nextInt();
System.out.print("Enter the customer's name that you are looking for: ");
String name = scan.nextLine();
//int rowNum;
// Search given row
XSSFRow row = sheet.getRow(searchRows);
try {
for (int j = 4; j < rowEnd; j++) {
Row r = sheet.getRow(j);
if (name.equalsIgnoreCase(name)) {
row.getCell(j).getStringCellValue();
}
// skip to next iterate if that specific cell is empty
if (r == null)
continue;
}
} catch (Exception e){
System.out.println("Something went wrong.");
}
}
}
ps. I know that this will be very confusing, but please feel free to ask for any kind of questions to help you get rid of the confusion and help me either because this has been a problem for me. Thank you very much and I will super appreciated for your help. Currently using apache poi, vscode, java.
I would iterate over the rows in the sheet and get the string content of cell 7 (H) from each row. If that string fulfills the requirement equalsIgnoreCase the searched value, that row is one of the result rows, else not.
One could collect the result rows in a List<Row>. Then this List contains the result rows after that.
Example:
ExcelWorkbook.xlsx:
Code:
import org.apache.poi.ss.usermodel.*;
import java.util.List;
import java.util.ArrayList;
import java.io.FileInputStream;
public class ExcelReadRowsByColumnValue {
public static void main(String[] args) throws Exception {
String filePath = "./ExcelWorkbook.xlsx";
String toSearch = "coresystem";
int searchColumn = 7; // column H
List<Row> results = new ArrayList<Row>();
DataFormatter dataFormatter = new DataFormatter();
Workbook workbook = WorkbookFactory.create(new FileInputStream(filePath));
FormulaEvaluator formulaEvaluator = workbook.getCreationHelper().createFormulaEvaluator();
Sheet sheet = workbook.getSheetAt(0);
for (Row row : sheet) { // iterate over all rows in the sheet
Cell cellInSearchColumn = row.getCell(searchColumn); // get the cell in seach column (H)
if (cellInSearchColumn != null) { // if that cell is present
String cellValue = dataFormatter.formatCellValue(cellInSearchColumn, formulaEvaluator); // get string cell value
if (toSearch.equalsIgnoreCase(cellValue)) { // if cell value equals the searched value
results.add(row); // add that row to the results
}
}
}
// print the results
System.out.println("Found results:");
for (Row row : results) {
int rowNumber = row.getRowNum()+1;
System.out.print("Row " + rowNumber + ":\t");
for (Cell cell : row) {
String cellValue = dataFormatter.formatCellValue(cell, formulaEvaluator);
System.out.print(cellValue + "\t");
}
System.out.println();
}
workbook.close();
}
}
Result:

Apache-poi “Compile error: Type mismatch”

I use Apache-poi 3.9 into my Struts 1.3.10 project.
I have two errors when i compile in this functionality:
private boolean parserHSSFSheet(HSSFSheet pageAccord, StringBuffer idPaa, StringBuffer idGroupe,
StringBuffer idFournisseur, StringBuffer idFamille, StringBuffer periode, Map<Integer, Marque> mapMarque,
Map<Integer, Ristournable> mapRistournable, Map<Integer, PerimetreProduitEnum> mapTypeDeclaration,
Map<Integer, FamilleDeProduitsNomenclature> mapFamille, Map<Integer, String> mapMarqueProduit,
TreeMap<Integer, TreeMap<Integer, BigDecimal>> mapColonneAdherentMontant,
TreeMap<Integer, BigDecimal> mapAdherentQuantite) throws Exception {
...
for (Iterator<HSSFRow> rit = pageAccord.rowIterator(); rit.hasNext();) {
HSSFRow row = (HSSFRow) rit.next();
String typeCellule = "";
for (Iterator<HSSFCell> cit = (Iterator<HSSFCell>) row.cellIterator(); cit.hasNext();) {
HSSFCell cell = cit.next();
if (cell.getCellNum() == ((short) 0)) {
...
}
Errors:
pageAccord.rowIterator();
Type mismatch: cannot convert from Iterator to Iterator
And
(Iterator<HSSFCell>) row.cellIterator();
Cannot cast from Iterator to Iterator
Have you seen the docs?? https://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/HSSFSheet.html says that rowIterator returns java.util.Iterator<Row> so you cannot cast it "onwards". The same is regarding cell etc.
change
Iterator<HSSFRow> rit = pageAccord.rowIterator(); rit.hasNext();
To
Iterator<Row> rit = pageAccord.rowIterator(); rit.hasNext();
And do the same for the cellIterator
Second cast, Cell into HSSFCell should work if iterator indeed will return compatibile type with HSSFCell.
As per the API docs a call to
pageAccord.rowIterator() returns a java.util.Iterator<Row>. See here.
row.cellIterator() returns a java.util.Iterator<Cell>. See here.
Both Row and Cell are only interfaces. Still I would work with those when possible and defer the explicit downcasting to places where this is actually necessary (and allowed).
Thus: Amend your iterators to comply with the types listed above (this could also mean using a generic Iterator<?> in places) and only downcast later (such as in your HSSFRow row = (HSSFRow) rit.next();).
Please find the below program for the quick solution
workbook = WorkbookFactory.create(new FileInputStream(envFilePath + "\\"+ listOfFiles[i].getName()));
// Get the first sheet.
Sheet sheet = workbook.getSheetAt(0);
// Get the first cell.
Row row = sheet.getRow(0);
Cell cell = row.getCell(0);
Test program which can help you
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
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.ss.usermodel.WorkbookFactory;
public class TestExcelFile {
public static void main(String[] args) {
String envFilePath = System.getenv("AZURE_FILE_PATH");
// upload list of files/directory to blob storage
File folder = new File(envFilePath);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
System.out.println("File " + listOfFiles[i].getName());
Workbook workbook;
try {
workbook = WorkbookFactory.create(new FileInputStream(envFilePath + "\\"+ listOfFiles[i].getName()));
// Get the first sheet.
Sheet sheet = workbook.getSheetAt(0);
// Get the first cell.
Row row = sheet.getRow(0);
Cell cell = row.getCell(0);
// Show what is being read.
System.out.println(cell.toString());
for (Cell cell1 : row) {
System.out.println(cell1.toString());
}
} catch (InvalidFormatException | IOException e) {
e.printStackTrace();
}
}
}
}
}

Read only few columns from excel sheet

I'm writing a Java program to fetch data from Excel sheet.
From the below program, i'm able to retrieve the entire data.
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
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 ReadData {
#SuppressWarnings({ "resource", "null" })
public static void main(String[] args) throws IOException {
// get file
FileInputStream fin = new FileInputStream(
new File("C:\\A2015.xlsx"));
// create book holding object
XSSFWorkbook wb = new XSSFWorkbook(fin);
// get sheet
XSSFSheet sheet = wb.getSheetAt(0);
// iterate through rows
Iterator<Row> rowIt = sheet.rowIterator();
while (rowIt.hasNext()) {
XSSFRow row = (XSSFRow) rowIt.next();
// iterate through Columns
Iterator<Cell> colIt = row.cellIterator();
while (colIt.hasNext()) {
Cell cell = colIt.next();
System.out.println(cell.toString());
}
System.out.println();
}
}
}
But here my case is there are nearly 45-47 columns and out of there there is some data which is not required(for me, but needed for some other teams). Every column has a heading, and out of these 45-47 columns i want to pull data only from 12 columns, and there are randomly placed between the rest of columns in Excel sheet.
My question is, is there a way to iterate through all the rows and get data from these 12 columns only by using the Heading, If so can you please let me know how to extract it.
I'm using Apache POI.
Thanks
public static short getCellNum(String cellCode)throws InvalidNameException{
char[] cellCodeU = cellCode.toUpperCase().toCharArray();
int length = cellCodeU.length;
int cellNumber = 0;
for (int j=0;j<length;j++){
if (cellCodeU[j]<'A' || cellCodeU[j]>'Z')
throw new InvalidNameException("Wrong column index: " + cellCode);
cellNumber = cellNumber*CELL_NUMBER_IN_SHEET + (cellCodeU[j]-64);
}
cellNumber-=1;
if (cellNumber<0)
throw new InvalidNameException("Wrong column index: " + cellCode);
return (short)cellNumber;
}
String columnsToRead = new String[]{"AA", "AB", "AU"};
while (rowIt.hasNext()) {
XSSFRow row = (XSSFRow) rowIt.next();
for (int a = 0; a < columnsToRead.length; a++){
Cell cell = getCell(getCellNum(columnsToRead[a]));
System.out.println(cell.toString());
}
}

Java : Need a collection type or method to extract all of data from Excel Sheet

I was trying to extract all of excel data: so I tried using Linkedhashmap within a LinkedHashmap (as in the code). The first Integer is analogous to row number, the second to column number and the String to cell values. When I store the values of columns and string (from inner hashmap to outer hashmap) the previous values (if any) are getting overwritten. This is observed even though I am using a new key value. Please see the sample code for clarification. Please suggest a method so that previous can be retrieved successfully or any other collection which can be used in this case.
Code:
public class test
{
public static void main(String[] args)
{
LinkedHashMap<Integer,LinkedHashMap<Integer,String>> values = new LinkedHashMap<Integer,LinkedHashMap<Integer,String>>();
LinkedHashMap<Integer,String> innerValues = new LinkedHashMap<Integer,String>();
innerValues.put(1, "FirstSetValue1");
innerValues.put(2, "FirstSetValue2");
values.put(1, innerValues);
System.out.println(values);
innerValues.put(1, "SecondSetValue1");
innerValues.put(2, "SecondSetValue2");
values.put(2, innerValues);
System.out.println(values);
}
}
Actual Output :
{1={1=FirstSetValue1, 2=FirstSetValue2}}
{1={1=SecondSetValue1, 2=SecondSetValue2}, 2={1=SecondSetValue1, 2=SecondSetValue2}}
Expected Output :
{1={1=FirstSetValue1, 2=FirstSetValue2}}
{1={1=FirstSetValue1, 2=FirstSetValue1}, 2={1=SecondSetValue1, 2=SecondSetValue2}}
I am fine with getting all the data from excel using poi, but I am having problem to put all the data into a collection(so that it could be retrieved successfully).
Yes Because the key is same, so it is overriding the previous values
Try this...
public static void main(String[] args)
{
LinkedHashMap<Integer,LinkedHashMap<Integer,String>> values = new LinkedHashMap<Integer,LinkedHashMap<Integer,String>>();
LinkedHashMap<Integer,String> innerValues = new LinkedHashMap<Integer,String>();
innerValues.put(1, "FirstSetValue1");
innerValues.put(2, "FirstSetValue2");
values.put(1, innerValues);
System.out.println(values);
innerValues = new LinkedHashMap<Integer,String>();
innerValues.put(1, "SecondSetValue1");
innerValues.put(2, "SecondSetValue1");
values.put(2, innerValues);
System.out.println(values);
}
This sample code may help you
1 Importing classes
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFRow;
2 Class name and and main method
public static void main( String [] args ) {
try {
InputStream input = new BufferedInputStream(
new FileInputStream("sample.xls"));
POIFSFileSystem fs = new POIFSFileSystem( input );
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
3 Itearting and displaying the results from sheet
Iterator rows = sheet.rowIterator();
while( rows.hasNext() ) {
HSSFRow row = (HSSFRow) rows.next();
System.out.println("\n");
Iterator cells = row.cellIterator();
while( cells.hasNext() ) {
HSSFCell cell = (HSSFCell) cells.next();
if(HSSFCell.CELL_TYPE_NUMERIC==cell.getCellType())
System.out.print( cell.getNumericCellValue()+" " );
else
if(HSSFCell.CELL_TYPE_STRING==cell.getCellType())
System.out.print( cell.getStringCellValue()+" " );
else
if(HSSFCell.CELL_TYPE_BOOLEAN==cell.getCellType())
System.out.print( cell.getBooleanCellValue()+" " );
else
if(HSSFCell.CELL_TYPE_BLANK==cell.getCellType())
System.out.print( "BLANK " );
else
System.out.print("Unknown cell type");
}
}
} catch ( IOException ex ) {
ex.printStackTrace();
}
}
}

Categories