Code:parses through the excel file using poi and prints the output in the console and also creates a new excel file to show the output.
XSSFWorkbook workbook = new XSSFWorkbook(fileName);
XSSFSheet sheet = workbook.getSheetAt(0);
XSSFRow row ;
XSSFCell cell;
Iterator<Row> rows = sheet.rowIterator();
while(rows.hasNext())
{
row = (XSSFRow)rows.next();
Iterator<Cell> cells = row.cellIterator();
while(cells.hasNext())
{
cell = (XSSFCell)cells.next();
switch(cell.getCellType())
{
case Cell.CELL_TYPE_BOOLEAN: System.out.println(cell.getBooleanCellValue()+"\t\t");
break;
case Cell.CELL_TYPE_NUMERIC: System.out.println(cell.getNumericCellValue()+ "\t\t");
break;
case Cell.CELL_TYPE_STRING:System.out.println(cell.getStringCellValue()+ "\t\t");
break;
}
}System.out.println("");
}fileName.close();
FileOutputStream out = new FileOutputStream(new File("C://data.xlsx"));
workbook.write(out);
out.close();
Output:
Id
Name
Location
Role
Salary
111.0
Kumar
Chennai
Developer
1000.0
112.0
Larsen
Bangalore
Developer
2000.0
Queries:
1. How to get the output in the same format as in excel?
2. How to store the output in a DTO object?
try this way to add Values DTO
Create one Student DTO with properties like and setter and getters with Id,Name,Location,Role,Salary
while(rows.hasNext())
{
row = (XSSFRow)rows.next();
Iterator<Cell> cells = row.cellIterator();
StudentDTO std = new StudentDTO();
while(cells.hasNext())
{
cell = (XSSFCell)cells.next();
switch(cell.getCellType())
{
case Cell.CELL_TYPE_BOOLEAN: System.out.println(cell.getBooleanCellValue()+"\t\t");
std.setId(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_NUMERIC: System.out.println(cell.getNumericCellValue()+ "\t\t");
std.setName(cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:System.out.println(cell.getStringCellValue()+ "\t\t");
std.setLocation(cell.getStringCellValue());
break;
}
}System.out.println("");
}
Related
I have saved contact details of the same type in the same cell(e.g person has more than one email address) I have saved them as a list in one cell but I'm not able to read them when iterating through my excel sheet. I can only read the currently selected/displayed, other options are ignored. I'm using java
//Read sheet inside the workbook by its name
Sheet _workSheet = _workbook.getSheet(sheetName);
//Iterate through each rows
Iterator<Row> rowIterator = _workSheet.iterator();
while(rowIterator.hasNext())
{
//Get Each Row
Row row_ = rowIterator.next();
//Iterator through each column of each row
Iterator<Cell> cellIterator = row_.cellIterator();
while(cellIterator.hasNext())
{
Cell cell = cellIterator.next();
//Checking the cell format
switch(cell.getCellType())
{
case Cell.CELL_TYPE_NUMERIC:
System.out.println(cell.getNumericCellValue()+"\n");
break;
case Cell.CELL_TYPE_STRING:
System.out.println(cell.getStringCellValue()+"\n");
break;
case Cell.CELL_TYPE_BOOLEAN:
System.out.println(cell.getBooleanCellValue()+"\n");
break;
case Cell.CELL_TYPE_BLANK:
System.err.println(cell.getStringCellValue()+" .....empty cell");
break;
}
}
System.err.println("");
}
In cell "A2" I'm expecting to get two values (emailone, emailTwo)
These did the trick;
List<XSSFDataValidation> dataValidations = sheet.getDataValidations();
Iterator<XSSFDataValidation> iterator = dataValidations.iterator();
XSSFDataValidation dataValidation = iterator.next();
String[] explicitListValues = dataValidation.getValidationConstraint().getExplicitListValues();
I'm reading an excel-file (file extension xlsx) using org.apache.poi 3.15.
This is my code:
try (FileInputStream fileInputStream = new FileInputStream(file); 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_NUMERIC:
System.out.print(cell.getNumericCellValue() + "(Integer)\t");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "(String)\t");
break;
}
}
System.out.println("");
}
} catch (Exception e) {
e.printStackTrace();
}
I get a warning that cell.getCellType() is deprecated. Can anyone tell me the alternative?
The accepted answer shows the reason for the deprecation but misses to name the alternative:
CellType getCellTypeEnum()
where the CellType is the enum decribing the type of the cell.
The plan is to rename getCellTypeEnum() back to getCellType() in POI 4.0.
You can use:
cell.getCellTypeEnum()
Further to compare the cell type, you have to use CellType as follows:-
if(cell.getCellTypeEnum() == CellType.STRING){
.
.
.
}
You can Refer to the documentation. Its pretty helpful:-
https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Cell.html
Use getCellType()
switch (cell.getCellType()) {
case BOOLEAN :
//To-do
break;
case NUMERIC:
//To-do
break;
case STRING:
//To-do
break;
}
FileInputStream fis = new FileInputStream(new File("C:/Test.xlsx"));
//create workbook instance
XSSFWorkbook wb = new XSSFWorkbook(fis);
//create a sheet object to retrieve the sheet
XSSFSheet sheet = wb.getSheetAt(0);
//to evaluate cell type
FormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator();
for(Row row : sheet)
{
for(Cell cell : row)
{
switch(formulaEvaluator.evaluateInCell(cell).getCellTypeEnum())
{
case NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t");
break;
case STRING:
System.out.print(cell.getStringCellValue() + "\t");
break;
default:
break;
}
}
System.out.println();
}
This code will work fine. Use getCellTypeEnum() and to compare use just NUMERIC or STRING.
From the documentation:
int getCellType()
Deprecated. POI 3.15. Will return a CellType enum in the future.
Return the cell type. Will return CellType in version 4.0 of POI. For forwards compatibility, do not hard-code cell type literals in your code.
It looks that 3.15 offers no satisfying solution: either one uses the old style with Cell.CELL_TYPE_*, or we use the method getCellTypeEnum() which is marked as deprecated.
A lot of disturbances for little add value...
For POI 3.17 this worked for me
switch (cellh.getCellTypeEnum()) {
case FORMULA:
if (cellh.getCellFormula().indexOf("LINEST") >= 0) {
value = Double.toString(cellh.getNumericCellValue());
} else {
value = XLS_getDataFromCellValue(evaluator.evaluate(cellh));
}
break;
case NUMERIC:
value = Double.toString(cellh.getNumericCellValue());
break;
case STRING:
value = cellh.getStringCellValue();
break;
case BOOLEAN:
if(cellh.getBooleanCellValue()){
value = "true";
} else {
value = "false";
}
break;
default:
value = "";
break;
}
You can do this:
private String cellToString(HSSFCell cell) {
CellType type;
Object result;
type = cell.getCellType();
switch (type) {
case NUMERIC : //numeric value in excel
result = cell.getNumericCellValue();
break;
case STRING : //String Value in Excel
result = cell.getStringCellValue();
break;
default :
throw new RuntimeException("There is no support for this type of value in Apche POI");
}
return result.toString();
}
I'm reading an excel-file (file extension xlsx) using org.apache.poi 3.15.
This is my code:
try (FileInputStream fileInputStream = new FileInputStream(file); 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_NUMERIC:
System.out.print(cell.getNumericCellValue() + "(Integer)\t");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "(String)\t");
break;
}
}
System.out.println("");
}
} catch (Exception e) {
e.printStackTrace();
}
I get a warning that cell.getCellType() is deprecated. Can anyone tell me the alternative?
The accepted answer shows the reason for the deprecation but misses to name the alternative:
CellType getCellTypeEnum()
where the CellType is the enum decribing the type of the cell.
The plan is to rename getCellTypeEnum() back to getCellType() in POI 4.0.
You can use:
cell.getCellTypeEnum()
Further to compare the cell type, you have to use CellType as follows:-
if(cell.getCellTypeEnum() == CellType.STRING){
.
.
.
}
You can Refer to the documentation. Its pretty helpful:-
https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Cell.html
Use getCellType()
switch (cell.getCellType()) {
case BOOLEAN :
//To-do
break;
case NUMERIC:
//To-do
break;
case STRING:
//To-do
break;
}
FileInputStream fis = new FileInputStream(new File("C:/Test.xlsx"));
//create workbook instance
XSSFWorkbook wb = new XSSFWorkbook(fis);
//create a sheet object to retrieve the sheet
XSSFSheet sheet = wb.getSheetAt(0);
//to evaluate cell type
FormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator();
for(Row row : sheet)
{
for(Cell cell : row)
{
switch(formulaEvaluator.evaluateInCell(cell).getCellTypeEnum())
{
case NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t");
break;
case STRING:
System.out.print(cell.getStringCellValue() + "\t");
break;
default:
break;
}
}
System.out.println();
}
This code will work fine. Use getCellTypeEnum() and to compare use just NUMERIC or STRING.
From the documentation:
int getCellType()
Deprecated. POI 3.15. Will return a CellType enum in the future.
Return the cell type. Will return CellType in version 4.0 of POI. For forwards compatibility, do not hard-code cell type literals in your code.
It looks that 3.15 offers no satisfying solution: either one uses the old style with Cell.CELL_TYPE_*, or we use the method getCellTypeEnum() which is marked as deprecated.
A lot of disturbances for little add value...
For POI 3.17 this worked for me
switch (cellh.getCellTypeEnum()) {
case FORMULA:
if (cellh.getCellFormula().indexOf("LINEST") >= 0) {
value = Double.toString(cellh.getNumericCellValue());
} else {
value = XLS_getDataFromCellValue(evaluator.evaluate(cellh));
}
break;
case NUMERIC:
value = Double.toString(cellh.getNumericCellValue());
break;
case STRING:
value = cellh.getStringCellValue();
break;
case BOOLEAN:
if(cellh.getBooleanCellValue()){
value = "true";
} else {
value = "false";
}
break;
default:
value = "";
break;
}
You can do this:
private String cellToString(HSSFCell cell) {
CellType type;
Object result;
type = cell.getCellType();
switch (type) {
case NUMERIC : //numeric value in excel
result = cell.getNumericCellValue();
break;
case STRING : //String Value in Excel
result = cell.getStringCellValue();
break;
default :
throw new RuntimeException("There is no support for this type of value in Apche POI");
}
return result.toString();
}
I have a row iterator that goes through excel sheet and gets every cell value in that row. I have successfully printed the values out, row by row, but I'd now like to store each cell in a row in separate variables so that I can pass them to Application Module where they will be used as parameters in an insert function. How to store cell value in variables ? Thanks. Here is the code:
try {
InputStream is = file.getInputStream();
HSSFWorkbook workbook = new HSSFWorkbook(is);
HSSFSheet sheet = workbook.getSheetAt(0);
System.out.print("File is up and the size is " + file.getLength() + " bytes\n");
Iterator<Row> rowIterator = sheet.iterator();
if (rowIterator.hasNext())
rowIterator.next();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
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");
// System.out.print(cell.getNumericCellValue()+ "\t");
break;
}
}
System.out.println("");
}
// workbook.close();
// file.close();
}
catch (IOException e) {
System.out.print("greška");
}
For anyone wondering how to do this. Iterate through every row and store it in an arrayList, and then store every ArrayList into another ArrayList. It should look like this ArrayList>. After you get that object send it to your Application module where you "unpack" your ArrayList with an enhanced for loop. After that extract elements from the array into variables and insert them in your view object.
I have created this code to read the contents of excel files using Apache POI. I am using eclipse as editor but when i ran the code i have problem in the line that I have in bold. What's the problem?
The content of excel is the following:
Emp ID Name Salary
1.0 john 2000000.0
2.0 dean 4200000.0
3.0 sam 2800000.0
4.0 cass 600000.0
import java.io.*;
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.poifs.filesystem.POIFSFileSystem;
public class ExcelRead {
public static void main(String[] args) throws Exception {
File excel = new File ("C:\\Users\\Efi\\Documents\\test.xls");
FileInputStream fis = new FileInputStream(excel);
HSSFWorkbook wb = new HSSFWorkbook(fis);
HSSFSheet ws = wb.getSheet("Input");
int rowNum = ws.getLastRowNum()+1;
int colNum = ws.getRow(0).getLastCellNum();
String[][] data = new String[rowNum][colNum];
for (int i=0; i<rowNum; i++){
HSSFRow row = ws.getRow(i);
for (int j=0; j<colNum; j++){
HSSFCell cell = row.getCell(j);
String value = cellToString(cell);
data[i][j] = value;
System.out.println("The value is" + value);
}
}
}
public static String cellToString (HSSFCell cell){
int type;
Object result;
type = cell.getCellType();
switch(type) {
case 0://numeric value in excel
result = cell.getNumericCellValue();
break;
case 1: //string value in excel
result = cell.getStringCellValue();
break;
case 2: //boolean value in excel
result = cell.getBooleanCellValue ();
break;
default:
***throw new RunTimeException("There are not support for this type of
cell");***
}
return result.toString();
}
}
There are additional cell types besides the ones you are capturing in your switch statement. You have cases for 0 (CELL_TYPE_NUMERIC), 1 (CELL_TYPE_STRING), and 2, but 2 is CELL_TYPE_FORMULA. Here are the additional possible values:
3: CELL_TYPE_BLANK
4: CELL_TYPE_BOOLEAN
5: CELL_TYPE_ERROR
Use the Cell constants for the cell type in your switch statement instead of integer literals, and use all 6 of them to capture all possible cases.
And as #Vash has already suggested, include the actual cell type in your RuntimeException message.
Check this library that I've created for reading both XLSX, XLS and CSV files pretty easily. It uses Apache POI for processing excel files and converts excel rows into a list of Java beans based on your configuration.
Here is an example:
RowConverter<Country> converter = (row) -> new Country(row[0], row[1]);
ExcelReader<Country> reader = ExcelReader.builder(Country.class)
.converter(converter)
.withHeader()
.csvDelimiter(';')
.sheets(1)
.build();
List<Country> list;
list = reader.read("src/test/resources/CountryCodes.xlsx");
list = reader.read("src/test/resources/CountryCodes.xls");
list = reader.read("src/test/resources/CountryCodes.csv");
With following excel and bean files:
public static class Country {
public String shortCode;
public String name;
public Country(String shortCode, String name) {
this.shortCode = shortCode;
this.name = name;
}
}
Excel:
Code Country
ad Andorra
ae United Arab Emirates
af Afghanistan
ag Antigua and Barbuda
...
Using XSSFWorkbook and XSSFSheet did not help me read .xls, but I used this code and it helps me read the .xls and xlsx files:
public static void readExcelFile(File file) throws IOException, InvalidFormatException {
Workbook workbook = WorkbookFactory.create(new File(file.toString()));
Integer sheet = workbook.getNumberOfSheets();
DataFormatter dataFormatter = new DataFormatter();
for (int i = 0; i < sheet; i++) {
Sheet s = workbook.getSheetAt(i);
Iterator<Row> rowIterator = s.rowIterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
printCellValue(cell);
// both work perfect
// printCellValue(cell);
/*String cellValue = dataFormatter.formatCellValue(cell);
System.out.print(cellValue + "\t");*/
}
System.out.println();
}
}
}
public static void printCellValue(Cell cell) {
switch (cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getRichStringCellValue().getString());
break;
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
System.out.print(cell.getDateCellValue());
} else {
System.out.print(cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_FORMULA:
System.out.print(cell.getCellFormula());
break;
case Cell.CELL_TYPE_BLANK:
System.out.print(" ");
break;
default:
System.out.print("");
}
System.out.print("\t");
}
You should amend that RuntimeException with information about what type is not supported with your switch statement. Then you will be able to add support for it, so no exception will be thrown.
So to see the picture of what your program is doing instead of
throw new RunTimeException("There are not support for this type of cell");
you should add
throw new RunTimeException("There are not support for type with id ["+type+"] of cell");
This will only, inform you what do you miss. How to handle this situation is up to you.