2010-11-04 53 views
0

我正在编程创建Excel电子表格(在C#/ .Net中使用the fabulous EPPlus library)并传入一组单元格范围(基于字符串)和自定义格式字符串以应用于这些范围。正则表达式RegEx验证自定义Excel格式

// Struct: 
public struct ExcelColumnFormat 
{ 
    public string CellRangeDefinition; 
    public string ExcelFormatString; 
} 

-

// Usage 
ExcelHelper.ExcelColumnFormat[] formats = new ExcelHelper.ExcelColumnFormat[1]; 
formats[0].ExcelFormatString = "$#,##0.00"; 
formats[0].CellRangeDefinition = "I:I"; 

-

// Consumption/application of those formats 
foreach (ExcelColumnFormat format in formats) 
{ 
    // Make sure that there are non-zero or null strings passed in 
    if (!String.IsNullOrEmpty(format.ExcelFormatString) && !String.IsNullOrEmpty(format.CellRangeDefinition)) 
     ws.Cells[format.CellRangeDefinition].Style.Numberformat.Format = format.ExcelFormatString; 
} 

我已经检查IsNullOrEmpty的字符串,但我想把验证的另一个水平测试,如果自定义格式字符串,实际上,有效的Excel格式。这是一个link to the Office help file that describes the rules around Excel Formats

现在的问题是:考虑到自定义Excel格式中可用的许多排列,这是一个值得的尝试,RegEx看起来如何?

在此先感谢!

+0

我敢肯定,你可以编写一个正则表达式来验证格式字符串,但这对作者来说是相当繁琐的。而且你冒着任何遗漏或错误的可能会拒绝一个有效的格式字符串。我不确定用恰当的词来描述它,但是这是一个算法复杂度较低的情况,但规则的复杂性很高。 – 2010-11-05 02:44:57

+0

我最终尝试使用VBA,但不想使用Interop/OLE/Excel API调用,并最终限制了筛选器的输入,而不是试图验证每个可能的排列组合。 – 2011-04-22 23:03:31

回答

0

或者你可以让VBA数字出来:

On Error GoTo complain 
junk = Format(dummyData,formatString) 
... 

的dummyData可能是在给定范围内的单元格的引用,如果数据类型是不知道。

+0

很棒的建议! – 2011-04-22 23:02:35