尝试使用C#打开我的Excel文件,并得到一个错误
我尝试从代码读取我的Exel文件,并收到System.InvalidCastException
:
Additional information: Unable to cast COM object of type 'System.__ComObject' to interface type 'Microsoft.Office.Tools.Excel.Worksheet'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{297DC8D9-EABD-45A1-BDEF-68AB67E5C3C3}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).
这个错误发生在objsheet = appExcel.ActiveWorkbook.ActiveSheet;
所以我尝试把它转换成objsheet = (Worksheet)appExcel.ActiveWorkbook.ActiveSheet;
但是这个错误依然存在
using Microsoft.Office.Interop.Excel; private static Microsoft.Office.Interop.Excel._Application appExcel; private static Microsoft.Office.Interop.Excel.Workbook newWorkbook = null; private static Microsoft.Office.Interop.Excel.Worksheet objsheet = null; private static string file = @"D:\file.xlsx"; //Method to initialize opening Excel static void excel_init(String path) { //appExcel = new Microsoft.Office.Interop.Excel.Application(); if (System.IO.File.Exists(path)) { // then go and load this into excel newWorkbook = appExcel.Workbooks.Open(file, true, true); int count = newWorkbook.Worksheets.Count; if (count > 0) { objsheet = (Microsoft.Office.Interop.Excel.Worksheet)newWorkbook.Worksheets[1]; } } else { MessageBox.Show("Unable to open file!"); System.Runtime.InteropServices.Marshal.ReleaseComObject(appExcel); appExcel = null; System.Windows.Forms.Application.Exit(); } }
newWorkbook为空。
尝试下面的代码,看看它是否有效,如果不让我们知道你有什么问题:
using Excel = Microsoft.Office.Interop.Excel; namespace Excel_Sample { public partial class YourClass { Excel.Application appExcel; Excel.Workbook newWorkbook; Excel.Worksheet objsheet; string file = @"D:\file.xlsx"; static void excel_init() { if (System.IO.File.Exists(file)) { //Start Excel and get Application object. appExcel = new Excel.Application(); //Get a workbook.; newWorkbook = (Excel.Workbook)(appExcel.Workbooks.Open(file)); int count = newWorkbook.Worksheets.Count; if (count > 0) { //Get Your Worksheet objsheet = (Excel.Worksheet)newWorkbook.ActiveSheet; } } else { MessageBox.Show("Unable to open file!"); System.Runtime.InteropServices.Marshal.ReleaseComObject(appExcel); appExcel = null; System.Windows.Forms.Application.Exit(); } } } }
Workbook.ActiveSheet属性可能不是程序打开的Excel文件的最佳select,因为它实际上可以返回非Worksheet对象
您可能需要考虑检查工作表数量和使用索引:
int count = newWorkbook.Worksheets.Count; if (count > 0) { objsheet = (Worksheet) newWorkbook.Worksheets[1]; }
尽量不要违反2点规则 – 你需要释放你所有的COM来正确closures你的应用程序和Excel。
编辑 :
您可以将Microsoft.Office.Interop.Excel与Microsoft.Office.Tools.Excel命名空间混合。
尝试声明和分配如下:
private static Microsoft.Office.Interop.Excel.Worksheet objsheet = null; ... objsheet = (Microsoft.Office.Interop.Excel.Worksheet) newWorkbook.Worksheets[1];
看起来像你正在使用
Microsoft.Office.Tools.Excel.Worksheet
代替
Microsoft.Office.Interop.Excel.Worksheet
这就是为什么你得到一个无效的转换exception。