C# Net中的Excel样式条件数字格式
我需要使用Excel条件格式字符串来格式化.Net应用程序中的数字。对于不熟悉Excel格式的用户,Excel格式字符串如下所示:C# Net中的Excel样式条件数字格式,c#,.net,excel,number-formatting,C#,.net,Excel,Number Formatting,我需要使用Excel条件格式字符串来格式化.Net应用程序中的数字。对于不熟悉Excel格式的用户,Excel格式字符串如下所示: [>=2]#,##0.0;[<=-2]-#,##0.0;#,##0.00 [>=2]#,##0.0;[您必须自己实现格式化,但您可以通过使用接口和连接到.NET现有的格式化框架 下面是一个如何实现的示例。条件格式类由多个条件格式对象组成。条件格式类有一个谓词和一个格式。条件格式将搜索所有条件格式对象按顺序查找第一个where谓词为true,并使用关联的
[>=2]#,##0.0;[<=-2]-#,##0.0;#,##0.00
[>=2]#,##0.0;[您必须自己实现格式化,但您可以通过使用接口和连接到.NET现有的格式化框架
下面是一个如何实现的示例。条件格式
类由多个条件格式
对象组成。条件格式
类有一个谓词
和一个格式
。条件格式
将搜索所有条件格式
对象按顺序查找第一个where谓词
为true,并使用关联的格式
。格式化程序使用字母“Z”作为格式字符串
class ConditionalFormat<T> where T : IFormattable {
public Func<T, Boolean> Predicate { get; set; }
public String Format { get; set; }
public static readonly Func<T, Boolean> Tautology = _ => true;
}
class ConditionalFormatter<T> : Collection<ConditionalFormat<T>>, IFormatProvider, ICustomFormatter
where T : IFormattable {
public const String FormatString = "Z";
readonly CultureInfo cultureInfo;
public ConditionalFormatter(IEnumerable<ConditionalFormat<T>> conditionalFormats)
: this(conditionalFormats, null) { }
public ConditionalFormatter(IEnumerable<ConditionalFormat<T>> conditionalFormats, CultureInfo cultureInfo)
: base(conditionalFormats.ToList()) {
this.cultureInfo = cultureInfo;
}
public Object GetFormat(Type formatType) {
return formatType == typeof(ICustomFormatter) ? this : null;
}
public String Format(String format, Object arg, IFormatProvider formatProvider) {
if (arg.GetType() != typeof(T))
return HandleOtherFormats(format, arg);
var formatUpperCase = format.ToUpperInvariant();
if (formatUpperCase != FormatString)
return HandleOtherFormats(format, arg);
var value = (T) arg;
foreach (var conditionalFormat in this)
if (conditionalFormat.Predicate(value))
return ((IFormattable) value).ToString(conditionalFormat.Format, cultureInfo);
throw new InvalidOperationException(String.Format("No format matching value {0}.", value));
}
String HandleOtherFormats(String format, Object arg) {
var formattable = arg as IFormattable;
if (formattable != null)
return formattable.ToString(format, this.cultureInfo);
else if (arg != null)
return arg.ToString();
else
return String.Empty;
}
}
你需要写if/elseif语句,没有直接的方法
string numberToFormat = //state your number here
string FormattedString = null;
if(numberToFormat >2)
{
//Format 1
//e.g. FormattedString = String.Format("{0:0.00}", numberToFormat);
}
else if(numberToFormat < -2)
{
//Format 2
}
else
{
// Format Default
}
string numberToFormat=//在此处说明您的号码
string FormattedString=null;
如果(数字格式>2)
{
//格式1
//e、 g.FormattedString=String.Format(“{0:0.00}”,numberToFormat);
}
否则如果(数字格式<-2)
{
//格式2
}
其他的
{
//格式默认值
}
这是最短的方法。当然,您可以获得自己的条件格式化程序。另一个有趣的解决方案:有一个名为的库,其中包含一个条件格式化程序
您的示例的语法是:
var output = Smart.Format("{0:>=2?{0:#,##0.0}|<=-2?{0:-#,##0.0}|{0:#,##0.00}}", value);
var output=Smart.Format(“{0:>=2?{0:#,##0.0}”|
var output = Smart.Format("{0:>=2?{0:#,##0.0}|<=-2?{0:-#,##0.0}|{0:#,##0.00}}", value);