无法加载typesMicrosoft.Office.Interop.Excel._Application

当我尝试debugging读取Excel文件的代码时出现错误。 我想知道是否对“Microsoft.Office.Interop.Excel._Application”的引用是错误的,我得到以下错误。

是不是Microsoft.Office.Interop.Excel版本假设是12? 而不是从我的项目组装?

无法从程序集'Dialog,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null'加载types'Microsoft.Office.Interop.Excel._Application'。 该types被标记为符合types等同性的条件,但包含的程序集不作为完全信任加载。

当我尝试debugging代码之前,我可以进入该function,我得到exception。

 DataTable data = ExcelImport.GetDataFromFile(file); 

我的function

 public static DataSet GetDataFromFile(string fileName) { Application oXL; Workbook oWB; Worksheet oSheet; Range oRng; // Needed to fix culture problem with excel files. CultureInfo cult = System.Threading.Thread.CurrentThread.CurrentCulture; System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); try { // creat a Application object oXL = new Application(); // get WorkBook object oWB = oXL.Workbooks.Open(fileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value); // get WorkSheet object oSheet = (Worksheet)oWB.Sheets[1]; System.Data.DataTable dt = new System.Data.DataTable("dtExcel"); DataSet ds = new DataSet(); ds.Tables.Add(dt); //StringBuilder sb = new StringBuilder(); int jValue = oSheet.UsedRange.Cells.Columns.Count; int iValue = oSheet.UsedRange.Cells.Rows.Count; // get data columns for (int j = 1; j <= jValue; j++) { dt.Columns.Add("column" + j, Type.GetType("System.String")); } // get data in cell for (int i = 1; i <= iValue; i++) { var test = (Range)oSheet.Cells[i, 1]; if (!string.IsNullOrEmpty(test.Text)) { DataRow dr = ds.Tables["dtExcel"].NewRow(); for (int j = 1; j <= jValue; j++) { oRng = (Range)oSheet.Cells[i, j]; string strValue = oRng.Text.ToString(); dr["column" + j] = strValue; } ds.Tables["dtExcel"].Rows.Add(dr); } } oXL.Workbooks.Close(); System.Threading.Thread.CurrentThread.CurrentCulture = cult; return ds; } catch (Exception ex) { throw new Exception("Error reading excel file", ex); } } 

vcsjones表彰让我走上了正确的轨道。 在closuresembedded互操作程序集之后,我需要编辑web.config来信任Excel

 <system.web> <trust level="Full" originUrl="" /> 

这听起来像你有一个错误的参考,而不是错误的代码。 这个代码有没有工作? 您是否尝试删除对Excel Interop的引用并重新添加它? 由于它甚至没有进入你的方法,我的假设是,当系统试图加载引用的DLL,它崩溃。