使用Microsoft.Office.Interop.Excel从Excel中读取文本格式

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

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

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

在那之前,我使用下面的方法来读取同一个单元格的值:

 myworksheet.Cells[row, col].Value; 

并获得正确的价值。

当我尝试使用debugging器来读取myworksheet.Cells[row, col].DisplayFormat.Style.Font.Strikethrough我收到false。

当我尝试使用debugging器来读取格式的Font并看到它的属性,我得到:

截图

exception详情:

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。

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

通过debugging器访问(watch和immediate)引发的exception提示库版本可能已过时,但版本14似乎是正确的版本( http://www.microsoft.com/en-us/download /details.aspx?id=3508 )。

我错过了什么?

在VBA中,你通常只是直接调用Cells(r,c).Font ,没有Style。

find原因和解决办法…

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

而是检查是否有任何有删除线格式的单元格工作:

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

但是,这只工作是单元格的值是一个string(不工作,如果价值是布尔例如)。 – 通过仅适用于string,我的意思是对于其他格式,我得到一个exception。