How to read .xlsx file with apache poi? - java

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:

Related

How to read the Excel (xlsx) Header column Data Type using apache POI 4.X

I have been struggling to find out the way to read the data type for each of the header columns.
I am using Apache POI 4.1.2 to read the XLSX file format using
XSSFWorkbook Implementation.
Business use case: I have an excel with 22 cells( includes string, Numeric, date field)
if user tries to modify the date field to String or Numeric to String or vice versa. I need to throw the errow without even reading the data rows. Thoug
h I am able to handle the data rows in case user modifies the type ( date value to varchar, Numeric to String)
Sudo code snippet:
XSSFRow headerRow = sheet.getRow(rownum:0);
for(int cellNum=0; cellNum<22;cellNum++){
Cell cell = headerRow.getCell(cellNum);
System.out.println(cell.getCellType());
// This always returns the string even though the header row has date and numeric fields)
}
None of the search or recommendation helped me with any leads or solution so looking for a working solution.
There is no way you can identify column types based on headers. Headers are typically text (string) that we enter in the first row of the file. They do not hold any specific data type.
On the other hand if you have to understand column types then you have to read from 2nd row of the file (leaving the headers).
Here is some implementation which does pretty good job at analyzing column types. You can mention how many rows to consider for analysis and which sheet to analyze
Code:
import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
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 Test {
public static void main(String[] args) {
String excelFileName = "C:\\Users\\test\\Downloads\\test.xlsx";
int sheet_num = 0;
int maxRows_ToAnalyze = 5;
Map<Integer, String> result = analyzeColumnTypes(excelFileName, sheet_num, maxRows_ToAnalyze);
for(int i : result.keySet()) {
System.out.println("Column "+i+" is of type ==> "+result.get(i));
}
}
static String NUMERIC = "NUMERIC";
static String DATE = "DATE";
static String STRING = "STRING";
static String FORMULA = "FORMULA";
static String BLANK = "BLANK";
static String BOOLEAN = "BOOLEAN";
static String ERROR = "ERROR";
static String NOT_CONSISTENT = "NOT_CONSISTENT";
public static Map<Integer, String> analyzeColumnTypes(String excelFileName, int sheet_num, int maxRows_ToAnalyze){
Workbook workbook = null;
Map<Integer, String> columnTypeMap = new HashMap<Integer, String>();
Map<Integer, Set<String>> tempMap = new HashMap<>();
Pattern p = Pattern.compile("[^0-9\\.]", Pattern.CASE_INSENSITIVE);
try {
FileInputStream excelFile = new FileInputStream(new File(excelFileName));
workbook = new XSSFWorkbook(excelFile);
Sheet sheet = workbook.getSheetAt(sheet_num);
int rows_in_sheet = sheet.getPhysicalNumberOfRows();
//if sheet rows are less than number of rows to analyze then analyze all the rows
if(rows_in_sheet<maxRows_ToAnalyze) {
maxRows_ToAnalyze = rows_in_sheet;
}
//i=1 because we dont want to read header rows
//header rows are typically strings
for(int i=1; i<=maxRows_ToAnalyze; i++) {
Row row = sheet.getRow(i);
int column_count = row.getPhysicalNumberOfCells();
for(int j=0; j<column_count; j++) {
tempMap.putIfAbsent(j, new HashSet<>());
Cell cell = row.getCell(j);
if(cell.getCellType().equals(CellType.NUMERIC)) {
Matcher m = p.matcher(cell.toString());
boolean match = m.find();
if(match) {
tempMap.get(j).add(DATE);
} else {
tempMap.get(j).add(NUMERIC);
}
} else if(cell.getCellType().equals(CellType.STRING)) {
tempMap.get(j).add(STRING);
} else if(cell.getCellType().equals(CellType.FORMULA)) {
tempMap.get(j).add(FORMULA);
} else if(cell.getCellType().equals(CellType.BLANK)) {
tempMap.get(j).add(BLANK);
} else if(cell.getCellType().equals(CellType.BOOLEAN)) {
tempMap.get(j).add(BOOLEAN);
} else if(cell.getCellType().equals(CellType.ERROR)) {
tempMap.get(j).add(ERROR);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
for(int colnum: tempMap.keySet()) {
if(tempMap.get(colnum).size()>1) {
columnTypeMap.put(colnum, NOT_CONSISTENT);
} else {
for(String coltype: tempMap.get(colnum)) {
columnTypeMap.put(colnum, coltype);
}
}
}
return columnTypeMap;
}
}

How to access perticular data in excel sheet

actually i want to fetch a particular data from excel sheet (.xls and .xlsx) like i have a column name email in my excel sheet and i want to fetch only that column. This is my code which is already i wrote but this is fetching all the details.Sorry for my grammar.
package readfile;
import java.io.File;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
public class reademail {
public static void main(String[] args) throws Exception
{
File f=new File("C:\\Users\\LQRP0023\\Desktop\\try.xls");
Workbook wb=Workbook.getWorkbook(f);
Sheet s=wb.getSheet(0);
int row=s.getRows();
int col=s.getColumns();
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
Cell c=s.getCell(j,i);
System.out.print(c.getContents());
}
System.out.println("");
// TODO Auto-generated method stub
} }}
You probably want to use the CellReference utility class to help you out.
You can then do something like:
Sheet sheet = workbook.getSheet("MyInterestingSheet");
CellReference ref = new CellReference("B12");
Row r = sheet.getRow(ref.getRow());
if (r != null) {
Cell c = r.getCell(ref.getCol());
}
That will let you find the cell at a given Excel-style reference
You need to check the Cell type and call the appropriate method to get the value, e.g.:
switch(cell.getCellType()){
case Cell.CELL_TYPE_STRING:
String stringValue = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_NUMERIC:
Number numericValue = cell.getNumericCellValue();
break;
}
For cell with Date, you can use HSSFDateUtil class to check the date formatted cell and get the value, e.g.:
if(HSSFDateUtil.isCellDateFormatted(cell)){
Date dateValue = cell.getDateCellValue();
}

perform operations on excel data sheet using java

there are four columns in excel sheet
I need to perform operations on three columns and display the result on the fourth one.
Image with data in excel
If I perform B9-D9 then the result is equal to C9.
when this happens the output should be as "matched".
i need to know how to access each row and column and perform the necessary operation on it.
See if you can help me and let me know if any additional details are required.
package com.infy;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;
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.xssf.usermodel.XSSFWorkbook;
public class ReconMatch {
public static void main(String[] args) throws IOException,
FileNotFoundException{
// TODO Auto-generated method stub
String excelFilePath ="C:/Users/akshay.kuchankar/Documents/demo.xlsx";
FileInputStream inputStream = new FileInputStream(new
File(excelFilePath));
Workbook workbook = new XSSFWorkbook(inputStream);
Sheet firstSheet = workbook.getSheetAt(0);
Iterator<Row> iterator = firstSheet.iterator();
while (iterator.hasNext()) {
Row nextRow = iterator.next();
Iterator<Cell> cellIterator = nextRow.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
//what should be the basic approach or the syntax to perform the operaiton??
}
System.out.println();
}
workbook.close();
inputStream.close();
}
}
for(int i= 0; i<firstSheet.getRow(0).getCell(0).getNumericCellValue(); i++)
{
FGAmount = firstSheet.getRow(1).getCell(1).getNumericCellValue();
// System.out.println(FGAmount);
difference = firstSheet.getRow(1).getCell(3).getNumericCellValue();
value = FGAmount + difference;
}
alconAmount = firstSheet.getRow(1).getCell(2).getNumericCellValue();
// result = firstSheet.getRow(1).getCell(4).getStringCellValue();
}
}
try {
if(value== alconAmount){
firstSheet.getRow(1).getCell(4).setCellValue("Manual Matched");
System.out.println("matched");
}
} catch (Exception e) {
e.printStackTrace();
System.out.println(e);
}
// System.out.println(result);
workbook.close();
inputStream.close();
Take a look at the API for your library:
https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Cell.html
You can interact with the cell in a number of ways, for example:
cell.setCellValue("My new value");
As for how to get values form cells and check against them you can do something a bit like this example where we do a bit of math and compare the values:
//Value of row 9, column 1 (column B)
String B9 = firstSheet.getRow(9).getCell(1).getStringCellValue();
//Value of row 9, column 2 (column C)
String D9 = firstSheet.getRow(9).getCell(2).getStringCellValue();
//Value of row 9, column 3 (column D)
String D9 = firstSheet.getRow(9).getCell(3).getStringCellValue();
//do math B9 - D9
double value = Double.parseDouble(B9) - Double.parseDouble(D9);
//check if C9 matches the result of B9 - D9
if(value == Double.parseDouble(C9))
{
//if it matches set cell E9 to display "Matched" and print out a message
firstSheet.getRow(9).getCell(4).setCellValue("matched");
System.out.println("matched");
}
I have not tested this code, but it should point you in the right direction.
Obviously there are things you should do like putting this in a loop rather than hard coding values, and you should check the column name to the make sure you have the right column before getting your values, and then you should check that the cell is a number and not text etc.
Edit in reply to your comment. Here is some code that will go over every row in a sheet except row 1 and will do exactly the same thing as in my example above and write "matched" in column E if column B - column D is equal to column C:
Iterator<Row> iterator = firstSheet.iterator();
while (iterator.hasNext()) {
Row nextRow = iterator.next();
//Check to make sure we skip the first row because that has all the column names:
if (nextRow.getRowNum() != 0){
//Get cell values of the current row
String columnB = nextRow.getCell(1).getStringCellValue();
String columnC = nextRow.getCell(2).getStringCellValue();
String columnD = nextRow.getCell(3).getStringCellValue();
try{
//do math column B - column D
double value = Double.parseDouble(columnB) - Double.parseDouble(columnD);
//check if column C matches the result of (column B - column D)
if(value == Double.parseDouble(columnC)){
//if it matches set text in column E to "matched"
nextRow.getCell(4).setCellValue("matched");
//print to console showing if a row matched
System.out.println("Row " + (nextRow.getRowNum()+1) + " matched");
}
}
catch(NumberFormatException nfe){
//do nothing here, this will happen if a cell contains text instead of numbers
}
catch(NullPointerException npe){
//Something else happened, you can probably ignore this as well but it will pay to throw a stack trace just in case something is wrong with this code
npe.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());
}
}

When getting cell content using Apache-POI Library, I get both "Cannot get a numeric value from a text cell" and the reverse of that. How do I fix it?

I realize the question is a little confusing, but I didn't know how else to word it. Anyway, here is the original code:
private void readFile(String excelFileName) throws FileNotFoundException, IOException {
XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(excelFileName));
if (workbook.getNumberOfSheets() > 1){
System.out.println("Please make sure there is only one sheet in the excel workbook.");
}
XSSFSheet sheet = workbook.getSheetAt(0);
int numOfPhysRows = sheet.getPhysicalNumberOfRows();
XSSFRow row;
XSSFCell num;
for(int y = 1;y < numOfPhysRows;y++){ //start at the 2nd row since 1st should be category names
row = sheet.getRow(y);
poNum = row.getCell(1);
item = new Item(Integer.parseInt(poNum.getStringCellValue());
itemList.add(item);
y++;
}
}
private int poiConvertFromStringtoInt(XSSFCell cell){
int x = Integer.parseInt(Double.toString(cell.getNumericCellValue()));
return x;
}
I am getting the following error:
Exception in thread "main" java.lang.IllegalStateException: Cannot get a numeric value from a text cell
at org.apache.poi.xssf.usermodel.XSSFCell.typeMismatch(XSSFCell.java:781)
at org.apache.poi.xssf.usermodel.XSSFCell.getNumericCellValue(XSSFCell.java:199)
Even if I change it to get either a string using XSSFCell.getStringCellValue() or even XFFSCell.getRichTextValue, I get the reverse of the above error message (and I am making sure to ultimately make it an int using Integer.parseInt(XSSFCell.getStringCellValue()).
The error then reads:
Exception in thread "main" java.lang.IllegalStateException: Cannot get a text value from a numeric cell
at org.apache.poi.xssf.usermodel.XSSFCell.typeMismatch(XSSFCell.java:781)
at org.apache.poi.xssf.usermodel.XSSFCell.getNumericCellValue(XSSFCell.java:199)
I know for a fact that the excel spreadsheet column is in fact a string. I can't change the excel sheet as it is uploaded else where always using the same format and formatting each column first takes up to much processing time.
Any suggestions?
[Solution] Here is the solution code I came up with from #Wivani's help:
private long poiGetCellValue(XSSFCell cell){
long x;
if(cell.getCellType() == 0)
x = (long)cell.getNumericCellValue();
else if(cell.getCellType() == 1)
x = Long.parseLong(cell.getStringCellValue());
else
x = -1;
return x;
}
Use This as reference
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
System.out.println(cell.getRichStringCellValue().getString());
break;
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
System.out.println(cell.getDateCellValue());
} else {
System.out.println(cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_BOOLEAN:
System.out.println(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_FORMULA:
System.out.println(cell.getCellFormula());
break;
default:
System.out.println();
}
You can get value as String using the format defined for this cell :
final DataFormatter df = new DataFormatter();
final XSSFCell cell = row.getCell(cellIndex);
String valueAsString = df.formatCellValue(cell);
Thanks to this answer.
Just use cell.setCellType(1); before reading cell value and get it as String always, after that you can use it in your own format(type).
Ravi
Use the below code to read any data type from xcels using poi.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
*
* #author nirmal
*/
public class ReadWriteExcel {
public static void main(String ar[]) {
ReadWriteExcel rw = new ReadWriteExcel();
rw.readDataFromExcel();
}
Object[][] data = null;
public File getFile() throws FileNotFoundException {
File here = new File("test/com/javaant/ssg/tests/test/data.xlsx");
return new File(here.getAbsolutePath());
}
public Object[][] readDataFromExcel() {
final DataFormatter df = new DataFormatter();
try {
FileInputStream file = new FileInputStream(getFile());
//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();
int rownum = 0;
int colnum = 0;
Row r=rowIterator.next();
int rowcount=sheet.getLastRowNum();
int colcount=r.getPhysicalNumberOfCells();
data = new Object[rowcount][colcount];
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
//For each row, iterate through all the columns
Iterator<Cell> cellIterator = row.cellIterator();
colnum = 0;
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
//Check the cell type and format accordingly
data[rownum][colnum] = df.formatCellValue(cell);
System.out.print(df.formatCellValue(cell));
colnum++;
System.out.println("-");
}
rownum++;
System.out.println("");
}
file.close();
} catch (Exception e) {
e.printStackTrace();
}
return data;
}
}
I got also this bug with POI version 3.12final.
I think that the bug is registered there : https://bz.apache.org/bugzilla/show_bug.cgi?id=56702 and I put a comment there with my analysis.
Here is the workaround I used : The exception was risen by HSSFCell.getNumericCellValue which was called by DateUtil.isCellDateFormatted. DateUtil.isCellDateFormatted does 2 things :
1) check the value type of the cell by calling HSSFCell.getNumericCellValue and then DateUtil.isValidExcelDate(), which is almost pointless here I think.
2) check if the format of the cell is a date format
I copied the code of topic 2) above in a new function 'myIsADateFormat' and used it instead of DateUtil.isCellDateFormatted (that is quite dirty to copy library code, but it works...) :
private boolean myIsADateFormat(Cell cell){
CellStyle style = cell.getCellStyle();
if(style == null) return false;
int formatNo = style.getDataFormat();
String formatString = style.getDataFormatString();
boolean result = DateUtil.isADateFormat(formatNo, formatString);
return result;
}
If you need to check the value type first, you can use this too :
CellValue cellValue = evaluator.evaluate(cell);
int cellValueType = cellValue.getCellType();
if(cellValueType == Cell.CELL_TYPE_NUMERIC){
if(myIsADateFormat(cell){
....
}
}
Documentation clearly says not to setCellType to 1 instead use the DataFormatter like how Thierry has explained:
https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Cell.html#setCellType(int)
Ravi's solution works :
Just use cell.setCellType(1); before reading cell value and get it as String always, after that you can use it in your own format(type).

Categories