使用OpenXml操作Excel,以下方法用于在添加列时修改Cell的CellReference属性。

以下方法实现了递增Excel中单元格的CellReference的功能,只支持两位字母。

 1 public static string CellReferenceIncrement(string cellReference)
 2 {
 3     Match m1 = Regex.Match(cellReference, "^([A-Z]+)");
 4     Match m2 = Regex.Match(cellReference, @"(\d+)$");
 5 
 6     string value = m1.Value;
 7     List<char> newChars = new List<char>();
 8     for (int i = value.Length - 1; i >= 0; )
 9     {
10         if (value[i] == 'Z')
11         {
12             newChars.Insert(0, 'A');
13             if ((i - 1) >= 0)
14                 newChars.Insert(0, (char)((int)value[i - 1] + 1));
15             else
16                 newChars.Insert(0, 'A');
17             break;
18         }
19         else
20         {
21             newChars.Insert(0, (char)((int)value[i] + 1));
22             if ((i - 1) >= 0)
23                 newChars.Insert(0, value[i - 1]);
24             break;
25         }
26     }
27     return string.Join("", newChars) + m2.Value;
28 }

以下为测试代码:

1 static void Main(string[] args)
2 {
3     List<string> tList = new List<string>() { "A2", "Z3", "AA3", "AZ9", "WF20" };
4     foreach (string s in tList)
5         Console.WriteLine(CellReferenceIncrement(s));
6 }

以下为输出结果:

posted @ 2016-09-08 23:07  qing_sun  阅读(2857)  评论(0编辑  收藏  举报