C# – 是否可以使用函数信函(A1)与workSheet.Cells?

我最近使用PowerShell来自动化一些东西,我可以简单地使用A1,A2等与C#,似乎是使用[1,1],(坐标样式)的要求,否则你会得到一个types不匹配。 这是我正在使用的代码:

//Generating User and Password int startCoordI = Int32.Parse(startCoord); int endCoordI = Int32.Parse(endCoord); int userCoordI = Int32.Parse(userCoord); int passwordCoordI = Int32.Parse(passwordCoord); int value = startCoordI; string Username = Convert.ToString(workSheet.Cells[userCoord, startCoordI].Value); MessageBox.Show(Username); string Password = Convert.ToString(workSheet.Cells[passwordCoord, startCoordI].Value); MessageBox.Show(Password); try { for (I = startCoordI; I <= endCoordI; I++) { System.Diagnostics.ProcessStartInfo proccessStartInfo = new System.Diagnostics.ProcessStartInfo("net", "user " + Username + " " + Password + " /add /passwordchg:no"); System.Diagnostics.Process proc = new System.Diagnostics.Process { StartInfo = proccessStartInfo }; proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.UseShellExecute = false; proccessStartInfo.CreateNoWindow = true; proc.Start(); //new user value++; Username = Convert.ToString(workSheet.Cells[userCoord, value].Value); Password = Convert.ToString(workSheet.Cells[passwordCoord, value].Value); } } catch (Exception ex) { MessageBox.Show(ex.Message); } 

这本质上不是一个问题,但是能够使用A1风格的坐标是很好的。 谢谢!

不是固有的,但创build一个扩展方法来为你做这件事真的很容易(我没有安装Excel,所以如果任何types是错误的更正);):

 public static class ExcelExtensions { public static Range Named(this Range Cells, string CellName) { char cellLetter = CellName.Substring(0, 1).ToUpper()[0]; int xCoordinate = (cellLetter - 'A') + 1; int yCoordinate = int.Parse(CellName.Substring(1)); return Cells[yCoordinate, xCoordinate]; } } 

现在你可以做:

 workSheet.Cells.Named("B3").Value ..... 

在我看来,如果您尝试使用BA1或AAA1这样的方法,将会出现错误。

这应该是正确的:

 public static class ExcelExtensions { public static exc.Range Named(this exc.Range Cells, string CellName) { //Get Letter char[] charArray = CellName.ToCharArray(); string strLetter = string.Empty; foreach (char letter in charArray) { if (Char.IsLetter(letter)) strLetter += letter.ToString(); } //Convert Letter to Number double value = 0; if (strLetter.Length > 1) { foreach (char letter in strLetter) { if (value == 0) { value = (letter - 'A' + 1) * Math.Pow(26, (strLetter.Length -1)); } else { value += (letter - 'A' + 1); } } } else { char[] letterarray = strLetter.ToCharArray(); value = (letterarray[0] - 'A') + 1; } // ReadOut Number string strNumber = string.Empty; foreach (char numChar in CellName.ToCharArray()) { if (Char.IsNumber(numChar)) strNumber += numChar.ToString(); } return Cells[strNumber, value]; } } 

我知道,这是一个凌乱的代码,但它的工作:)