【问题标题】:Excel table access multidimentional array by index throws "Exception from HRESULT: 0x800A03EC"} System.Runtime.InteropServices.COMExceptionExcel 表通过索引访问多维数组抛出“HRESULT 异常:0x800A03EC”} System.Runtime.InteropServices.COMException
【发布时间】:2020-12-17 16:59:44
【问题描述】:

您好,我想读取一个 excel 表格,以在进入下一行之前通过索引或标题名称访问一行的列,以便在某些条件下修改单元格。

这是我到目前为止所做的:

Excel.ListObject table = objSheet.ListObjects[1];
foreach (Excel.Range x in table.Range.Rows)
{
//I want to access to columns of current row here like x[ColumnHeaderName] or x[ColNumber]
//if (x[0,0] ...)
     //x[0,1] = ...;

}

我知道可以使用两个循环,但对我的情况没有帮助:

Excel.ListObject table = objSheet.ListObjects[1];
foreach (var x in table.Range.Rows.Value2)
{
foreach (var y in x)
//access column after column, for the current row
}

我尝试使用x[0,1] 没有成功,它抛出异常:

"Exception from HRESULT: 0x800A03EC"} System.Runtime.InteropServices.COMException.

Linq2Excel 阅读能力强,但写作能力强。

如何使用System.Object[,] 类型的变量“x”来通过索引或标题名称访问该行的列?

【问题讨论】:

  • 这个答案有用吗? - stackoverflow.com/a/46724947/755133
  • 我想修改excel文件中的表格并保存,答案是关闭excel文件。
  • 知道了。您看到什么异常消息?
  • C# 使用基于 0 的数组引用,您是否尝试过 x[0, 0] - x[0, n]
  • 我也试过x[0,0],它抛出了同样的异常。

标签: c# excel multidimensional-array excel-interop


【解决方案1】:

也许这不是最好的方法,但您可以使用Cells 索引号(从 1 开始)来做到这一点:

Excel.ListObject table = objSheet.ListObjects[1];
foreach (Excel.Range x in table.Range.Rows)
{
if (Cells[0].Value2 ...)
     Cells[1].Value2 = ...;

}

但是你必须根据你的excel表格的列数确定索引,如果你放置的索引大于你的列数,你会从下一行得到一个单元格。假设您有 5 列,如果您尝试访问索引 6,您将获得下一行的第一列,依此类推。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-21
    • 1970-01-01
    • 2021-05-05
    • 2015-05-08
    相关资源
    最近更新 更多