I\'m storing mix of numeric and non-numeric values in a single column in spreadsheet using C# and EPPlus. When I open spreadsheet with Excel it shows green triangles in the
From the EPPlus documentation:
My number formats does not work If you add numeric data as strings (like the original ExcelPackage does), Excel will treat the data as a string and it will not be formatted. Do not use the ToString method when setting numeric values.
string s="1000"
int i=1000;
worksheet.Cells["A1"].Value=s; //Will not be formatted
worksheet.Cells["A2"].Value=i; //Will be formatted
worksheet.Cells["A1:A2"].Style.Numberformat.Format="#,##0";
http://epplus.codeplex.com/wikipage?title=FAQ&referringTitle=Documentation
You really have 2 options using code:
change the .NumberFormat property of Range to TEXT (I believe equivalent in epplus is Cell[row, column].Style.NumberFormat.Format
)
prefix any number with '
(a single quote) - Excel then treats the number as TEXT - visually, it displays the number as is but the formula will show the single quote.
Alternatively, which I wouldn't recommend relying on
This is a derivation of TechnoPriest's answer that works for me - I've added handling of decimal values, and changed the name of the method to more accurately document its true raison d'etre:
public static void ConvertValueToAppropriateTypeAndAssign(this ExcelRangeBase range, object value)
{
string strVal = value.ToString();
if (!String.IsNullOrEmpty(strVal))
{
decimal decVal;
double dVal;
int iVal;
if (decimal.TryParse(strVal, out decVal))
{
range.Value = decVal;
}
else if (double.TryParse(strVal, out dVal))
{
range.Value = dVal;
}
else if (Int32.TryParse(strVal, out iVal))
{
range.Value = iVal;
}
else
{
range.Value = strVal;
}
}
else
{
range.Value = null;
}
}
You can check if your value is integer, convert it to int and assign number to cell's value. Then it will be saved as number, not string.
public static void SetValueIntOrStr(this ExcelRangeBase range, object value)
{
string strVal = value.ToString();
if (!String.IsNullOrEmpty(strVal))
{
double dVal;
int iVal;
if (double.TryParse(strVal, out dVal))
range.Value = dVal;
else if (Int32.TryParse(strVal, out iVal))
range.Value = iVal;
else
range.Value = strVal;
}
else
range.Value = null;
}