【发布时间】:2011-05-02 22:24:49
【问题描述】:
我在尝试调试读取 Excel 文件的代码时遇到错误。我想知道对“Microsoft.Office.Interop.Excel._Application”的引用是否错误,我收到以下错误。
Microsoft.Office.Interop.Excel 版本不应该是 12 吗?并且没有从我的项目程序集中加载?
无法加载类型 'Microsoft.Office.Interop.Excel._Application' 从程序集'对话框, 版本=1.0.0.0,文化=中性, PublicKeyToken=null'。类型是 标记为符合类型 等价,但包含 程序集未完全加载 值得信赖。
当我尝试调试代码时,我在进入函数之前得到了异常。
DataTable data = ExcelImport.GetDataFromFile(file);
我的功能
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);
}
}
【问题讨论】:
-
如果您使用的是 C# 4.0 编译器,请尝试关闭 Embedding Interop Assemblies。