我最近使用powershell使用Excel自动执行某些操作,我可以简单地使用A1,A2等。使用C#,似乎需要使用[1,1],(坐标样式)或者你得到一个类型不匹配。 这是我正在使用的代码:
//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样式坐标会很好。谢谢!
答案 0 :(得分:2)
不是固有的,但是创建一个扩展方法为你做这件事真的很容易(我没有安装Excel,所以如果任何类型的错误更正;)):( / p>
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 .....
答案 1 :(得分:0)
在我看来,如果你尝试用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];
}
}
我知道,这是一个混乱的代码,但它有效:)
答案 2 :(得分:0)
这对我来说似乎是最干净的方法。处理AD14列行问题。
public static Range Named(this Range Cells, string CellName)
{
int xCoordinate = Cells.Range[CellName].Column;
int yCoordinate = Cells.Range[CellName].Row;
return Cells[yCoordinate, xCoordinate];
}