0

大约在去年,我的 C# 代码在从 Excel 文件中导入数据方面运行良好:

Microsoft.Office.Interop.Excel.Application objExcel = new Microsoft.Office.Interop.Excel.Application();
            objExcel.Visible = false;
            objExcel.Workbooks.Open(TemplateFile, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
Microsoft.Office.Interop.Excel.Workbook TemplateWorkbook
Microsoft.Office.Interop.Excel.Range exRngFBCKIdent = null;
....

                foreach (Microsoft.Office.Interop.Excel.Worksheet objWorksheet in objExcel.ActiveWorkbook.Worksheets) //Loop through worksheets.
                {
                    // ...
                    try
                    {
                        exRngFBCKIdent = objWorksheet.get_Range("FBCKIDENT", Type.Missing);
                        ((Microsoft.Office.Interop.Excel._Worksheet)exRngFBCKIdent.Worksheet).Activate();
                    }
                    catch (Exception excException)
                    {
                        MessageBox.Show("ERROR: Range 'FBCKIDENT' was not found in the file - ensure this range is defined correctly and try again!", "Feedback Import", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return null;
                    }
...
}

然后突然对于特定的 Excel 文件,它开始在 objWorksheet.get_Range 代码行上引发异常。这是一个例外:

objWorksheet.get_Range("FBCKIDENT", Type.Missing)   'objWorksheet.get_Range("FBCKIDENT", Type.Missing)' threw an exception of type 'System.Runtime.InteropServices.COMException'    Microsoft.Office.Interop.Excel.Range {System.Runtime.InteropServices.COMException}
base    {"Exception from HRESULT: 0x800A03EC"}  System.Runtime.InteropServices.ExternalException {System.Runtime.InteropServices.COMException}

如果我尝试快速查看 objExcel 对象,则会收到以下错误:

Member 'Application' on embedded interop type 'Microsoft.Office.Interop.Excel.Workbook' cannot be evaluated while debugging since it is never referenced in the program. Consider casting the source object to type 'dynamic' first or building with the 'Embed Interop Types' property set to false when debugging

我花了很多时间研究可能的解决方案,包括 Interop 类型不能嵌入;但是,如果我更改 Microsoft.Office.Interop.Excel dll 的嵌入式互操作类型,我仍然会遇到相同的错误。我错过了一些明显的东西吗?有没有人有什么建议?TIA。

4

1 回答 1

0

请注意,我最终通过手动将数据复制到新的 Excel 文件并导入该文件来解决问题——我仍然不确定原始 Excel 文件到底出了什么问题。谢谢大家的建议。

于 2013-07-04T21:59:49.713 回答