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

时间:2021-10-09 01:19:35

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

 public static string CellReferenceIncrement(string cellReference)
{
Match m1 = Regex.Match(cellReference, "^([A-Z]+)");
Match m2 = Regex.Match(cellReference, @"(\d+)$"); string value = m1.Value;
List<char> newChars = new List<char>();
for (int i = value.Length - ; i >= ; )
{
if (value[i] == 'Z')
{
newChars.Insert(, 'A');
if ((i - ) >= )
newChars.Insert(, (char)((int)value[i - ] + ));
else
newChars.Insert(, 'A');
break;
}
else
{
newChars.Insert(, (char)((int)value[i] + ));
if ((i - ) >= )
newChars.Insert(, value[i - ]);
break;
}
}
return string.Join("", newChars) + m2.Value;
}

以下为测试代码:

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

以下为输出结果:

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAABgCAIAAADQG7YaAAABeUlEQVRoge2YS3LEMAgFdf9T6WjZpSYCHsjh46p5vdLIcmhLGFxZixBCnrH/Aq4OmLlj+bMcat0QTKC37Ja1pgn3sAacZNThlIp4jDkBj8ltA1V+C/q0CCHE56pJ9xWzuFZr9bceXa3+4GeykxrAmpdrSnisVX6CahhrftmHnqzlfkRYNxY6XY3B7ZkED86d/wKtI3W2wF2W70QIISFAN7T6dEfdUmO7Y/XGTOSjz2tt7XNv+Ati2VpuApWfoAyDd6sp3+XGRHKo/ATxGBhUmVnhb+cHtLoLxJFS28C6qzzrCSHkBNen5f3vtNYMSOCZgVb9O4O7TUdPVEOOaYHeN6nlhrTWFCY+eHprIz8nu7WCb9ykFgjfnVv4cMud1AQ6ZqwFJU6EEII4WptVvayeKEtXWj07tI55PLYuJZhlaQV76L+0wB99qZZ6+7u0gjn3UEu+hur7CJzytZbYqkiMW8scrXV/QMNakWUJTpbWMrJqC+TVBCdCSD0/CbBkrqKEZIAAAAAASUVORK5CYII=" alt="" />