【问题标题】:Reading text format from Excel using Microsoft.Office.Interop.Excel使用 Microsoft.Office.Interop.Excel 从 Excel 读取文本格式
【发布时间】:2012-07-26 00:57:52
【问题描述】:

我正在尝试阅读文本格式,例如Strikethough 属性通过

myworksheet.Cells[row, col].DisplayFormat.Style.Font.Strikethrough;

但是,无论实际的格式是什么,结果总是错误的。

就在此之前,我使用以下方法读取了同一单元格的值:

myworksheet.Cells[row, col].Value;

并得到正确的值。

当我尝试使用调试器读取 myworksheet.Cells[row, col].DisplayFormat.Style.Font.Strikethrough 时,我收到错误消息。

当我尝试使用调试器读取格式的 Font 并查看其属性时,我得到:

异常详情:

Strikethrough {System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Runtime.InteropServices.COMException: Old format or invalid type library. (Exception from HRESULT: 0x80028018 (TYPE_E_INVDATAREAD)) --- End of inner exception stack trace --- at System.RuntimeType.InvokeDispMethod(String name, BindingFlags invokeAttr, Object target, Object[] args, Boolean[] byrefModifiers, Int32 culture, String[] namedParameters) at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams) at System.Dynamic.IDispatchComObject.GetMembers(IEnumerable`1 names)} System.Reflection.TargetInvocationException

我在 Windows 7 SP1 x64 操作系统上安装了 Office 2010 x86,并且我从 .NET 4.0 项目中引用 Microsoft.Office.Interop.Excel 版本 14。

我使用相同的库以编程方式创建了 .xlsx 文件,并通过 Excel 的 UI 手动添加了文本格式。

通过调试器(监视和立即)访问引发的异常提示库版本可能已过时,但是版本 14 似乎是正确的版本 (http://www.microsoft.com/en-us/download/details.aspx?id=3508)。

我错过了什么?

【问题讨论】:

  • 在 VBA 中,您通常只需直接调用 Cells(r,c).Font,而不使用样式。这行得通吗?
  • @TimWilliams 是的,谢谢。添加为答案,我会接受。

标签: .net excel office-interop


【解决方案1】:

找到原因和解决办法...

显然,格式是每个字符,而不是每个单元格。

检查是否有任何具有删除线格式的单元格有效:

for (int ch = 1; ch <= cell.Characters.Count; ch++)
{
    if (cell.Characters[ch, 1].Font.Strikethrough)
    {
        hasStrikeThrough = true;
        break;
     }
}

但是,这仅适用于单元格的值是一个字符串(例如,如果 value 是 bool,则不起作用)。 - 仅适用于字符串,我的意思是对于其他格式我得到一个例外。

【讨论】:

    【解决方案2】:

    在 VBA 中,您通常只需直接调用 Cells(r,c).Font,而不使用 Style。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多