[英]VSTO write to a cell in Excel!
Why does this work: 为什么这样做:
((Excel.Worksheet)Application.ActiveSheet).get_Range("A1", "A1").Value2 = text;
But this doesn't: 但这不是:
Excel.Worksheet activeSheet = ((Excel.Worksheet)Application.ActiveSheet);
activeSheet.Cells[0, 0] = text;
I need to do it the second way as I need to loop with rowIndex and colIndex. 我需要第二种方式,因为我需要使用rowIndex和colIndex循环。 How can I do that? 我怎样才能做到这一点?
I get the error: 我收到错误:
An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in mscorlib.dll Additional information: Exception from HRESULT: 0x800A03EC mscorlib.dll中发生未处理的“System.Runtime.InteropServices.COMException”类型的异常附加信息:来自HRESULT的异常:0x800A03EC
The only thing you're missing (other than using 1 based indexes) is to cast the cell reference to a range explicitly: 您唯一缺少的是(除了使用基于1的索引之外)是将单元格引用显式地转换为范围:
Excel.Worksheet activeSheet = ((Excel.Worksheet)Application.ActiveSheet);
int endRow = 5;
int endCol = 6;
for(int idxRow = 1; idxRow <= endRow; idxRow++)
{
for(int idxCol = 1; idxCol <= endCol; idxCol)
{
((Excel.Range)activeSheet.Cells[idxRow, idxCol]).Value2 = "Kilroy wuz here";
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.