How to Add Validations(Numeric,Date) to a Particular Cell using POI - java

How to add a Integer Validation, Date Validation to a Particular Cell Using POI.
and validate after the user enters data, show an error message if data is wrong
thanks in advance

I once encountered a similar situation for validating an excel file. You can code like this:
if(cell != null){
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
//Validate String as required
break;
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
//Validate Date
} else {
//Validate Number
}
break;
default:
//Handle Default
}
}
I suggest that you write separate validation handlers for each type (string, number and date) and just invoke them from your switch case.

Related

Can you refer to case values inside the code block of the switch statement?

So can you do something like this in Java:
Can you get the value being switched on inside a switch expression
I have quite a few cases in my code which look like this (actual logic code removed for clarity reasons):
switch (weatherSystem.getRealClass().getSimpleName())
{
case "SyncWeatherSystem":
logger.info("initializing sync weather system");
…
break;
case "AsyncWeatherSystem":
logger.info("initializing async weather system");
…
break;
case "FixedWeatherSystem":
logger.info("initializing fixed weather system");
…
break;
case "NoWeatherSystem":
logger.info("initializing no weather system");
…
break;
}
And I really would love to do like:
switch (weatherSystem.getRealClass().getSimpleName())
{
case "SyncWeatherSystem":
logger.info("initializing {}", case.value);
…
break;
case "AsyncWeatherSystem":
logger.info("initializing {}", case.value);
…
break;
case "FixedWeatherSystem":
logger.info("initializing {}", case.value);
…
break;
case "NoWeatherSystem":
logger.info("initializing {}", case.value);
…
break;
}
Is this possible in Java?
No. It is not. But, weatherSystem.getRealClass().getSimpleName() is. I suggest you save that value to a local variable. And all your case(s) seem to do the same thing. So, as posted, you could simplify it. Like
String sName = weatherSystem.getRealClass().getSimpleName();
switch (sName)
{
case "SyncWeatherSystem":
case "AsyncWeatherSystem":
case "FixedWeatherSystem":
case "NoWeatherSystem":
logger.info("initializing {}", sName);
break;
}

XmlValueDisconnectedException when remove Formula

I trying to reade an Excel file with java poi. I iterate through the rows and then through the cells. To reade the cell i use this method:
private String readCell(Cell cell) {
try {
switch (cell.getCellType()) {
case NUMERIC:
if (format.isParseNumbersToInt()) {
return ((int) cell.getNumericCellValue()) + "";
} else {
return cell.getNumericCellValue() + "";
}
case STRING:
case _NONE:
return cell.getStringCellValue();
case FORMULA:
if (format.isUseCashedFormulaValue()) {
cell.removeFormula();
return readCell(cell);
} else {
return cell.getCellFormula() + "";
}
case BLANK:
return format.getBlankValue();
case BOOLEAN:
return cell.getBooleanCellValue() + "";
case ERROR:
if (format.isReadErrorCells()) {
return "ERROR_" + cell.getErrorCellValue();
} else {
return format.getErrorCellValue();
}
}
} catch (Exception e) {
throw new IllegalArgumentException("Failed to read cell: " + cell.getAddress(), e);
}
throw new IllegalStateException("Unknown CellType: " + cell.getCellType().name());
}
At one point the XmlValueDisconnectedException throws:
Caused by: org.apache.xmlbeans.impl.values.XmlValueDisconnectedException
at org.apache.xmlbeans.impl.values.XmlObjectBase.check_dated(XmlObjectBase.java:1274)
at org.apache.xmlbeans.impl.values.XmlObjectBase.getStringValue(XmlObjectBase.java:1529)
at org.apache.poi.xssf.usermodel.XSSFCell.convertSharedFormula(XSSFCell.java:491)
at org.apache.poi.xssf.usermodel.XSSFCell.getCellFormula(XSSFCell.java:469)
at org.apache.poi.xssf.usermodel.XSSFSheet.onDeleteFormula(XSSFSheet.java:4654)
at org.apache.poi.xssf.usermodel.XSSFCell.removeFormulaImpl(XSSFCell.java:571)
at org.apache.poi.ss.usermodel.CellBase.removeFormula(CellBase.java:182)
at de.heuboe.base.excel.controller.reader.ExcelReader.readCell(ExcelReader.java:356)
... 89 more
This Point looks the same as all others. The Point of the file:
enter image description here
in D219 is the string in the following cells is a referenze to the cell one row over, e.g. D220: "=D219" and D221: "=D220". The same for the columns E, F and G.
The hole file looks like this and works but at this point the programm crashes. And i don't know why.
According the StackTrace, there is a problem with a shared formula.
If you have formulas =D6, =D7, =D8, ... =D219, =D220, ... and so on in column D, then not for all cells the complete formula is stored. Instead only one cell stores the complete formula and following cells only store shared reference to the formula.
In OOXML this looks like so :
In XML of cell D8: <f ref="D8:D300" t="shared" si="1">D7</f>
In XML of cell D9:D300: <f t="shared" si="1"/>
This Excel behavior tends to be fragile if somewhat else than Excel manipulates rows containing such shared formulas.
Cell.removeFormula is a pretty new feature in apache poi. It might be buggy. But as it is designed it should know about such shared formulas and respect those. So to get what really leads to that XmlValueDisconnectedException one would need the Excel file. There one could have a look into the sheet's XML and check whether someting in the shared formula's XML is different from the default which is expected by XSSFCell.convertSharedFormula.
But do you really need Cell.removeFormula? Because if the goal is simply to get the cashed formula value instead of the formula string itself but to avoid evaluating, then one could get that cashed formula value the same way as the other cell values but dependent on the cached formula result type.
Example:
...
case FORMULA:
if (isUseCashedFormulaValue) {
//cell.removeFormula();
//return readCell(cell);
switch (cell.getCachedFormulaResultType()) {
case NUMERIC:
return String.valueOf(cell.getNumericCellValue());
case STRING:
return cell.getStringCellValue();
case BOOLEAN:
return String.valueOf(cell.getBooleanCellValue());
case ERROR:
return "ERROR_" + cell.getErrorCellValue();
}
} else {
return cell.getCellFormula();
}
...

Transforming if-else into switch case throws error [Java]

I tried to convert my if-else statements into a switch case but I had the following problem.
Old code:
if (properties.get("database").toString().equalsIgnoreCase("SQLSERVER")) {
manager = new CManagingSQLServer();
} else if (properties.get("database").toString().equalsIgnoreCase("ORACLE")){
manager = new CManagingOracle();
} else if (properties.get("database").toString().equalsIgnoreCase("MYSQL")){
manager = new CManagingMySQL();
} else {
System.out.println("Not supported DB: " + properties.get("database").toString() + "\n");
System.out.println("Supported DB:");
System.out.println("- ORACLE");
System.out.println("- SQLSERVER");
System.out.println("- MYSQL");
System.exit(0);
}
New code:
String database = properties.get("database").toString();
switch (database) {
case database.equalsIgnoreCase("SQLSERVER"):
manager = new CManagingSQLServer();
break;
case database.equalsIgnoreCase("ORACLE"):
manager = new CManagingOracle();
break;
case database.equalsIgnoreCase("MYSQL"):
manager = new CManagingMySQL();
break;
default:
System.out.println(database + "is not a supported database.");
System.exit(0);
break;
}
First, the String database threw an error that I have to change setting/property (actually don't know) into version 1.7?! After doing so, my cases are throwing now errors. They say: Type mismatch cannot convert from boolean to String.
I read other SO-thread and they said I have to try (String)something or something.ToString(). But both cases didn't work and I don't understand what changed with the above mentioned change to version 1.7.
And how can I make my cases work again?
Change database variable to
String database = properties.get("database").toString().toUpperCase();
And switch case to
case "SQLSERVER":
Currently, you are getting error because database.equalsIgnoreCase("SQLSERVER") returns boolean but you are switching on database which is a String.
Also, you need to use minimum of Java 7 because Java versions before that don't support switch case on String.
The problem you are facing is that in switch you pass a String typed database.
In case of section you want to work with boolean expression database.equalsIgnoreCase(...).
The easiest way to deal with that is to change the line:
String database = properties.get("database").toString();
to:
String database = properties.get("database").toString().toUpperCase();
and in case section use simple approach (as you have already upper cased database variable):
case "SQLSERVER"
instead of
case database.equalsIgnoreCase("SQLSERVER")
INFORMATION:
Switch expressions that work with strings are available from JDK 7.
you are missing the whole concept of switch case , you don't have to put equal condtion in your switch case.
just put like this it will work fine
String database = properties.get("database").toString().toUpperCase();
switch (database) {
case "SQLSERVER":
manager = new CManagingSQLServer();
break;
case "ORACLE":
manager = new CManagingOracle();
break;
case "MYSQL":
manager = new CManagingMySQL();
break;
default:
System.out.println(database + "is not a supported database.");
System.exit(0);
break;
}
Use the string value in case statements.
Case "SQLSERVER":

Apache POI for excel get dependent cells

I am writing a program that reads excel files using apache POI. I'm getting all the values, but I want to know which cells are dependent on others (using the formula for the cell).
I've tried using String formula = cell.getCellFormula(), but this just returns me the cell index (eg. H5). Is there any other way I can do this?
Here's my code for reading cells:
private void handleCell(int type,Cell cell)
{
switch (type)
{
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_FORMULA:
String form = cell.getCellFormula();
handleCell(cell.getCachedFormulaResultType(),cell);
break;
default :
}
}
have a look at org.apache.poi.ss.formula.FormulaParser.
It has a static method
public static Ptg[] parse(
java.lang.String formula,
FormulaParsingWorkbook workbook,
int formulaType,
int sheetIndex)
according to the documentation, it parses a formula string into a List of tokens in RPN order.
The tokens (Ptg = "parse things") can be checked for their type (REF/VALUE/ARRAY) using public final byte getPtgClass().
I have not tested it, but it may be the way to go. Parse the formula, then check each Ptg entry for the type (REF?) and get the destination cell.
See:
https://poi.apache.org/apidocs/org/apache/poi/ss/formula/FormulaParser.html
https://poi.apache.org/apidocs/org/apache/poi/ss/formula/ptg/Ptg.html

Reading in a text file and comparing text - Java

In my program I am reading in and parsing a file for resources.
I extract a string which represents the resource type, do a simple if then else statement to check if it matches any known types and throw an error if it doesn't:
if(type.toLowerCase() == "spritesheet") {
_type = ResourceType.Spritesheet;
} else if(type.toLowerCase() == "string") {
_type = ResourceType.String;
} else if(type.toLowerCase() == "texture") {
_type = ResourceType.Texture;
} else if(type.toLowerCase() == "num") {
_type = ResourceType.Number;
} else {
throw new Exception("Invalid Resource File - Invalid type: |" + type.toLowerCase() + "|");
}
Ignoring my bad naming and non descript exception, this statement is always going to the final else, even if type IS "spritesheet" as read in from the file, etc.
java.lang.Exception: Invalid Resource File - Invalid type: |spritesheet|
at Resource.Load(Resource.java:55) //Final else.
If I set type to "spritesheet" before this call, it works, so I'm wondering if it's some kind of encoding error or something?
I haven't done much work in java so I might be missing something simple :)
Assuming type is a String, you want to use String.equals() to test for equality. Using the == operator tests to see if the variables are references to the same object.
Also, to make your life easier, I would suggest using String.equalsIgnoreCase() as this will save you from calling toLowerCase().
Starting from Java 7 you can use Strings in switch statements! :)
The following should work:
switch (type.toLowerCase()) {
case "spritesheet": _type = ResourceType.Spritesheet; break;
case "string": _type = ResourceType.String; break;
case "texture": _type = ResourceType.Texture; break;
case "num": _type = ResourceType.Number; break;
default: throw new Exception("Invalid Resource File " +
"- Invalid type: |" + type.toLowerCase() + "|");
}
I haven't tried it yet, let me know how it goes!

Categories

Resources