使用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 }

以下為輸出結果:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM