c# - VSTO 写入 Excel 中的单元格!

标签 c# .net excel

为什么这样做:

((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/

相关文章:

c# - 什么是 "private .NET framework"?

java - Apache poi如何获取单元格坐标

c# - 如何在列表中添加时间跨度值

c# - 如何释放被占用的内存

excel - 将图片插入Excel单元格

excel - 如何加速 VBA 中的 For Each 循环?

c# - 如何使用证书 (.cer) 文件在 C# 中进行代码签名?

c# - 为什么我的记录在 mongodb upsert 场景中得到零 objectid?

c# - 处理 list 需要太多时间

c# - 没有 C# 的可空特性的可空类型实现