简体   繁体   English

如何使用 Excel Interop 检索与基于引用另一个 Excel 工作表的公式的 Excel 单元格关联的值?

[英]How can I retrieve the value associated with an Excel Cell that is based on a formula referencing another Excel Sheet using Excel Interop?

I am properly able to get the values of Excel cells using Excel interop with the following method:我可以通过以下方法使用 Excel 互操作正确获取 Excel 单元格的值:

public string ReadCell(object row, object column)
{
    try
    {
        if (m_Worksheet.Cells[row][column].Value != null)
        {
            return Convert.ToString(m_Worksheet.Cells[row][column].Value2);
        }
     }
     catch
     {
         //
     }
      
        return string.Empty;
    }
}

The above code works for ordinary text or number values.上面的代码适用于普通的文本或数字值。

When it is a formula -- for example, when I use a formula as following no text or value will appear: ='Data Selection'!B4当它是一个公式时——例如,当我使用下面的公式时,不会出现任何文本或值='Data Selection'!B4

The actual value of this cell is "Community Bank"这个单元格的实际值为“社区银行”

I ended up solving this problem.我最终解决了这个问题。 The else if case is actually what I was originally using, but it previously threw an exception in some instances (I cannot remember what the exact exception was). else if案例实际上是我最初使用的,但它之前在某些情况下抛出了异常(我不记得确切的异常是什么)。 I will go back later and improve my answer.稍后我会回去改进我的答案。

public string ReadCell(object row, object column)
{
    try
    {
        if (m_Worksheet.Cells[row][column].Value != null)
        {
            return Convert.ToString(m_Worksheet.Cells[row][column].Value2);
        }
        else if (m_Worksheet.Cells[row, column].Value != null)
        {
            return Convert.ToString(m_Worksheet.Cells[row, column].Value2);
        }
     }
     catch
     {
         //
     }

     return string.Empty;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM