我正在編程創建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看起來如何?
在此先感謝!
我敢肯定,你可以編寫一個正則表達式來驗證格式字符串,但這對作者來說是相當繁瑣的。而且你冒着任何遺漏或錯誤的可能會拒絕一個有效的格式字符串。我不確定用恰當的詞來描述它,但是這是一個算法複雜度較低的情況,但規則的複雜性很高。 – 2010-11-05 02:44:57
我最終嘗試使用VBA,但不想使用Interop/OLE/Excel API調用,並最終限制了篩選器的輸入,而不是試圖驗證每個可能的排列組合。 – 2011-04-22 23:03:31