为什么这样做:
((Excel.Worksheet)Application.ActiveSheet).get_Range("A1", "A1").Value2 = text;
但这不是:
Excel.Worksheet activeSheet = ((Excel.Worksheet)Application.ActiveSheet);
activeSheet.Cells[0, 0] = text;
我需要用第二种方法来做,因为我需要用 rowIndex 和 colIndex 循环。我该怎么做?
我得到错误:
An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in mscorlib.dll Additional information: Exception from HRESULT: 0x800A03EC
最佳答案
唯一缺少的(除了使用基于 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";
}
}
关于c# - VSTO 写入 Excel 中的单元格!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/856196/