c#中字母的增量

我正在Excel Using Open XML将我的数据导出到Excel Using Open XML 。 现在我想增加字母表,如columns 'A1' to 'B1',...'Z1', 'AA1'.

我已将’A1’分配给变量,我想将字母增加到’B1’。

请提供任何方法/代码,可以将字母’A1’增加到’B1′..’Z1’,’AA1’。

这可以做到:

 char c1 = 'A'; c1++; // c1 is 'B' now 

并且您可以将编号添加为字符串,甚至可以以相同的方式生成连接的字符:

伪代码:

 If Reached_Z Then Add_Another_A 

此示例使用能够从AZZ的迭代器。

 public static IEnumerable GetColumns() { string s = null; for (char c2 = 'A'; c2 <= 'Z' + 1; c2++) { for (char c = 'A'; c <= 'Z'; c++) { yield return s + c; } s = c2.ToString (); } } 

此示例从A1开始并经过AA1

 string currentCell = "A1"; int currentRow = int.Parse(Regex.Match(currentCell, @"\d+").Value); string currentCol = Regex.Match(currentCell, @"[AZ]+").Value; foreach (string column in GetColumns().Where (c => c >= currentCol && currentCol <= "AA")) { Console.WriteLine (column + currentRow); } 

此示例从C5开始,并通过接下来的26列进行枚举。

 int columnsToAdd = 26; currentCell = "C5"; currentRow = int.Parse(Regex.Match(currentCell, @"\d+").Value); currentCol = Regex.Match(currentCell, @"[AZ]+").Value; foreach (string column in GetColumns().Where (c => c >= currentCol)) { if (columnsToAdd--) == 0) break; Console.WriteLine (column + currentRow); } 

我认为这些function可以满足您的需求:

  public static string IncrementXLColumn(string Address) { var parts = System.Text.RegularExpressions.Regex.Matches(Address, @"([AZ]+)|(\d+)"); if (parts.Count != 2) return null; return incCol(parts[0].Value) + parts[1].Value; } private static string incCol(string col) { if (col == "") return "A"; string fPart = col.Substring(0, col.Length - 1); char lChar = col[col.Length - 1]; if (lChar == 'Z') return incCol(fPart) + "A"; return fPart + ++lChar; } 

此函数将采用A1到B1,Z1到AA1等字符串。还应该处理ZZ1到AAA1

这个方法将为您提供下一栏:

  private static Regex ALL_Z_REGEX = new Regex("^[zZ]+$"); static string GetNextColumn(string currentColumn) { // AZ would become BA char lastPosition = currentColumn[currentColumn.Length - 1]; if (ALL_Z_REGEX.IsMatch(currentColumn)) { string result = String.Empty; for (int i = 0; i < currentColumn.Length; i++) result += "A"; return result + "A"; } else if (lastPosition == 'Z') return GetNextColumn(currentColumn.Remove(currentColumn.Length - 1, 1)) + "A"; else return currentColumn.Remove(currentColumn.Length - 1, 1) + (++lastPosition).ToString(); } 

您可以使用字符串构建器来实现此目的。

  int length = value.Length; var lastString = value[length - 1]; if (lastString == 'Z') { if ((length - 2) >= 0) ++value[length - 2]; else value.Append('A'); value.Replace("Z", "A"); } else ++value[length - 1];