【问题标题】:VSTO write to a cell in Excel!VSTO 写入 Excel 中的单元格!
【发布时间】:2009-05-13 05:22:24
【问题描述】:

为什么会这样:

((Excel.Worksheet)Application.ActiveSheet).get_Range("A1", "A1").Value2 = text;

但这不是:

Excel.Worksheet activeSheet = ((Excel.Worksheet)Application.ActiveSheet);
activeSheet.Cells[0, 0] = text;

我需要使用第二种方式,因为我需要使用 rowIndex 和 colIndex 进行循环。我该怎么做?

我得到错误:

未处理的类型异常 'System.Runtime.InteropServices.COMException' 发生在 mscorlib.dll 附加 信息:HRESULT 异常: 0x800A03EC

【问题讨论】:

    标签: c# .net excel


    【解决方案1】:

    您唯一缺少的(除了使用基于 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";
        }
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-13
    • 2012-07-19
    • 2017-05-29
    相关资源
    最近更新 更多