NPOI does not evaluate 3d formula - npoi

I'm using NPOI to read data from Excel 2003 files. These files contains formulas like this SUM('1:2'!$C$17). NPOI recognized such formulas like SUM('1'!$C$17) (w/o sheet 2) and evaluate invalid result.
I'm using a regular code from NPOI examples, like
foreach (var row in docRows)
{
sb.AppendFormat("{0}\t", SomeCode);
rowCounter += 1;
sb.AppendFormat("{0}\t", rowCounter);
foreach (var col in docColumns)
{
ICell cell = sheet.GetRow(row).GetCell(col);
sb.AppendFormat("{0}\t", GetExcelCellValue(cell));
}
sb.AppendLine();
}
private string GetExcelCellValue(ICell cell)
{
string cellValue = string.Empty;
IFormulaEvaluator evaluator = _hssfworkbook.GetCreationHelper().CreateFormulaEvaluator();
evaluator.Evaluate(cell);
switch (evaluator.EvaluateInCell(cell).CellType)
{
case CellType.BLANK:
cellValue = string.Empty;
break;
case CellType.BOOLEAN:
cellValue = string.Empty;
break;
case CellType.NUMERIC:
cellValue = Convert.ToString(cell.NumericCellValue); //This is a trick to get the correct value of the cell. NumericCellValue will return a numeric value no matter the cell value is a date or a number.
break;
case CellType.STRING:
throw new ArgumentNullException();
cellValue = cell.StringCellValue;
break;
case CellType.ERROR:
cellValue = string.Empty;
break;
case CellType.FORMULA:
break;
}
return cellValue;
}

I have just encountered this problem and I solved it by
switch (cell.CellType)
{
case CellType.Blank:
cellValue = "";
break;
case CellType.Boolean:
cellValue = cell.BooleanCellValue.ToString();
break;
case CellType.Formula:
cellValue = cell.NumericCellValue.ToString();
break;
case CellType.Numeric:
cellValue = cell.NumericCellValue.ToString();
break;
case CellType.String:
cellValue = cell.StringCellValue;
break;
}

Related

Cannot read chinese characters in an excel file

I have developed a java application that will read an excel file containing chinese characters and convert it to multiple CSV files. The file is as below:
public class SplitterBean {
public static final Logger LOGGER = LoggerFactory.getLogger(SplitterBean.class);
public List<Map<String, String>> splitBody(XSSFWorkbook workbook) {
LOGGER.info("Inside SplitterBean, splitting: " + workbook.getNumberOfSheets());
Map<String, String> sheetMap = null;
List<Map<String, String>> sheetList = new ArrayList<Map<String,String>>();
int numberOfSheets = workbook.getNumberOfSheets();
XSSFFormulaEvaluator.evaluateAllFormulaCells(workbook);
for (int i = 0; i < numberOfSheets; i++) {
StringBuilder sb = new StringBuilder();
sheetMap = new HashMap<String, String>();
XSSFSheet sheet = workbook.getSheetAt(i);
String sheetName = sheet.getSheetName();
for (Row row : sheet) {
for (Cell cell : row) {
String cellValue = null;
LOGGER.info("Cell type is: " + cell.getCellType());
switch (cell.getCellType()) {
case NUMERIC:
cellValue = Double.toString(cell.getNumericCellValue());
break;
case STRING:
cellValue = cell.getStringCellValue();
break;
case BLANK:
cellValue = "";
break;
case FORMULA:
LOGGER.info("Reached formula cell, cell type is: " + cell.getCellType().toString());
switch (cell.getCellType()) {
case NUMERIC:
cellValue = Double.toString(cell.getNumericCellValue());
break;
case STRING:
cellValue = cell.getStringCellValue();
break;
case BLANK:
cellValue = "";
break;
default:
cellValue = "";
break;
}
default:
cellValue = "";
break;
}
sb.append(cellValue).append(",");
}
sb.append("\n");
}
sheetMap.put(sheetName, sb.toString());
sheetList.add(sheetMap);
}
return sheetList;
}
}
We are deploying our project as war file in Wildfly 17.0.1.FINAL. But when the CSV file is generated, the chinese characters are getting distorted. I guess this is due to server encoding which I need to change to UTF-8. Can anyone suggest me how to change server encoding in Wildfly 17.0.1.FINAL or how this issue can be solved?

Got Null result from Oracle even though the real result are decimal value

I am new to Oracle in Visual Studio,
I used Oracle.ManagedDataAccess as my reference,
The case is whenever I tried to retrieve decimal value from arithmetic in Oracle query, Its always return null
e.g
SELECT 26/3 FROM DUAL < ---- This code return null in my visual studio but has a value in TOAD.
Did I do it wrong ?
Here is my code to retrieve the value
List<object[]> result = new List<object[]>();
OracleDataReader data;
string constr = ConfigurationManager.ConnectionStrings["OraConnection"].ConnectionString;
using (OracleConnection con = new OracleConnection(constr))
{
string query = QueryString;
using (OracleCommand cmd = new OracleCommand(query))
{
cmd.Connection = con;
con.Open();
data = cmd.ExecuteReader();
try
{
if (data.HasRows)
{
while (data.Read())
{
object[] itemData = new object[data.FieldCount];
//Dictionary<string, string> itemData = new Dictionary<string, string>();
for (int i = 0; i < data.FieldCount; i++)
{
Type type = data.GetValue(i).GetType();
if (typeof(string) == type)
{
itemData[i] = data.GetString(i);
}
if (typeof(DateTime) == type)
{
itemData[i] = data.GetDateTime(i);
}
if (typeof(int) == type)
{
itemData[i] = data.GetInt32(i);
}
if (typeof(decimal) == type)
{
itemData[i] = data.GetDecimal(i);
}
if (typeof(bool) == type)
{
itemData[i] = data.GetBoolean(i);
}
if (typeof(TimeSpan) == type)
{
itemData[i] = data.GetTimeSpan(i);
}
if (typeof(Single) == type)
{
itemData[i] = Convert.ToDecimal(data.GetOracleDecimal(i).ToString());
}
}
result.Add(itemData);
}
}
else
{
Console.WriteLine("Rows not found.");
}
}
finally
{
data.Close();
}
con.Close();
}
}
return result;
UPDATED : It got null just for division which has decimal value. Addition, Substraction, multiplication has no issue
It seems your data type doesn't match any of your if expressions. As there is no default branch, itemData[i] remains null. I suggest something like the following to find the gap:
for (int i = 0; i < data.FieldCount; i++)
{
Type type = data.GetValue(i).GetType();
switch(type)
{
case typeof(string):
itemData[i] = data.GetString(i);
break;
case typeof(DateTime):
itemData[i] = data.GetDateTime(i);
break;
case typeof(int):
itemData[i] = data.GetInt32(i);
break;
case typeof(decimal):
itemData[i] = data.GetDecimal(i);
break;
case typeof(bool):
itemData[i] = data.GetBoolean(i);
break;
case typeof(TimeSpan):
itemData[i] = data.GetTimeSpan(i);
break;
case typeof(Single):
itemData[i] = Convert.ToDecimal(data.GetOracleDecimal(i).ToString());
break;
default:
MessageBox.Show("Unknown type " + type.Name);
break;
}
}
So, I got an advice to edit the oracle query
From (e.g.)
SELECT 26/7 FROM DUAL
TO
SELECT TO_CHAR(26/7) FROM DUAL
And yes it works
But still, I don't know why

Search for particular column and update it in linq EF 4.0

Basically table contain about 50 columns and I have to search for that particular column and update it.
lets say val == 27 then columnName will be Alarm27 and the "onOff" value I have to set in that Alarm27 column.
But question is how do I get this Alarm27 and just update it.
This is what I have tried so far.
public void UpdateAlarm(int val, bool onOff)
{
string alarmName = "Alarm" + val;
using (ESEntities context = new ESEntities())
{
var alarmid = context.OffShoreAlarms.Where(p => p.StationID == (int)TMStation.LQ).Select(p => p.OSAlarmID).FirstOrDefault();
var alarmMonitor = context.OfSAlarmMonitors.Where(p => p.OSAlarmID == alarmid).Select(p => p).FirstOrDefault();
switch (val)
{
case 1:
alarmMonitor.Alarm1 = onOff;
context.saveChanges();
break;
case 2:
alarmMonitor.Alarm2 = onOff;
context.SaveChanges();
break;
.
.
.
.
case 50:
alarmMonitor.alarm50 = onOff;
context.saveChanges();
break;
}
//TODO: context.SaveChanges(); do update operation..
}
}
I have not practically tried this but I think this may work for you.
string alarmName = "Alarm" + val;
context.OffShoreAlarms.Property(alarmName).CurrentValue = true;
You can change current Value of Your entity like this.
For more info check this Link

How should I be using the Kentico TreeNode.Update method?

I am trying to run the attached code to update some data for a particular document type but it is not actually updating anything.
My currentDocumentNodeId() method is pulling back a NodeId based on some other criteria and then each of these Nodes that it is getting is of the type HG.DocumentLibraryItem which have the columns IsPublic, IsRepMining, IsRepPower, IsRepProcess, and IsRepFlexStream. But when I call the update method and then pull back those Columns in the SQL table for this Custom Document Type, the values are all Null. Each of those columns in the HG.DocumentLibraryItem document type are set to boolean I have tried using the Node.SetValue() method and setting it to true and 1; neither way works to update that column.
Any ideas what I am doing wrong? Am I doing the call correctly?
See my code below:
public static void GetDocumentAreaAssignments()
{
var cmd = new SqlCommand
{
CommandText ="This is pulling back 2 rows, one with Id and one with Text",
CommandType = CommandType.Text,
Connection = OldDbConnection
};
OldDbConnection.Open();
try
{
using (SqlDataReader rdr = cmd.ExecuteReader())
{
var count = 0;
while (rdr.Read())
{
try
{
var documentId = TryGetValue(rdr, 0, 0);
var areaAssignment = TryGetValue(rdr, 1, "");
var currentDocumentNodeId = GetNodeIdForOldDocumentId(documentId);
var node = currentDocumentNodeId == 0
? null
: Provider.SelectSingleNode(currentDocumentNodeId);
if (node != null)
{
switch (areaAssignment.ToLower())
{
case "rep mining":
node.SetValue("IsRepMining", 1);
break;
case "rep power":
node.SetValue("IsRepPower", 1);
break;
case "rep process":
node.SetValue("IsRepProcess", 1);
break;
case "rep flexStream":
node.SetValue("IsFlexStream", 1);
break;
case "public":
node.SetValue("IsPublic", 1);
break;
}
node.Update();
Console.WriteLine("Changed Areas for Node {0}; item {1} complete", node.NodeID,
count + 1);
}
}
catch (Exception ex)
{
}
count++;
}
}
}
catch (Exception)
{
}
OldDbConnection.Close();
}
The coupled data (as IsRepMining field) are only updated when you retrieve a node that contains them. To do that you have to use overload of the SelectSingleNode() method with a className parameter. However I'd recommend you to always use the DocumentHelper to retrieve documents. (It will ensure you work with the latest version of a document...in case of workflows etc.)
TreeProviderInstance.SelectSingleNode(1, "en-US", "HG.DocumentLibraryItem")
DocumentHelper.GetDocument(...)
DocumentHelper.GetDocuments(...)

Update a single column to EF 6.0 using LINQ lambda ? MVC4

I want to save the data when i edit something in my data-table on enter .
On enter control goes to method in controller where actual update performs .
My code till this point:
public string UpdateData(int id, string value, int? rowId, int? columnPosition, int? columnId, string columnName)
{
var Leadsinfo = ser_obj1.Lead_List();
if (columnPosition == 0 && Leadsinfo.Any(c => c.Contact_Name.ToLower().Equals(value.ToLower())))
return "Lead with a name '" + value + "' already exists";
var Lead = Leadsinfo.FirstOrDefault(c => c.Lead_Id == id);
if (Lead == null)
{
return "Lead with an id = " + id + " does not exists";
}
switch (columnPosition)
{
case 0:
Lead.Contact_Name = value;
iWise_NeoEntities ooo = new iWise_NeoEntities();
break;
case 1:
Lead.Contact_Address = value;
break;
case 2:
Lead.Lead_Source = value;
break;
case 3:
Lead.Domain = value;
break;
default:
break;
}
return value;
}
In the above code i mentioned i need to write logic where it should save to DB upon any column editing . using lambda linq is easy i guess , But i dont know even how to start ?
Do i need to write save under each case?
You can create update method in database:
public void UpdateLead(Lead model)
{
var entity = db.Set<Lead>().Find(model.Id);
db.Entry<Lead>(entity).CurrentValues.SetValues(model);
db.SaveChanges();
}
And use it where you need:
switch (columnPosition)
{
case 0: Lead.Contact_Name = value; break;
case 1: Lead.Contact_Address = value; break;
case 2: Lead.Lead_Source = value; break;
case 3: Lead.Domain = value; break;
default: break;
}
iWise_NeoEntities ooo = new iWise_NeoEntities();
ooo.UpdateLead(Lead);

Resources