I get an error when trying to debug code that reads Excel files. I am wondering if it is wrong to refer to "Microsoft.Office.Interop.Excel._Application", I get the following error.
doesn't mean version Microsoft.Office.Interop.Excelshould be 12? and not loading from my project build?
Could not load type 'Microsoft.Office.Interop.Excel._Application' from the assembly 'Dialog, Version = 1.0.0.0, Culture = neutral, PublicKeyToken = zero. The type is marked as suitable for the equivalence type, but the containing assembly does not load as fully trusted.
When I try to debug code, I get an exception before I can enter the function.
DataTable data = ExcelImport.GetDataFromFile(file);
My function
public static DataSet GetDataFromFile(string fileName)
{
Application oXL;
Workbook oWB;
Worksheet oSheet;
Range oRng;
CultureInfo cult = System.Threading.Thread.CurrentThread.CurrentCulture;
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
try
{
oXL = new Application();
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);
oSheet = (Worksheet)oWB.Sheets[1];
System.Data.DataTable dt = new System.Data.DataTable("dtExcel");
DataSet ds = new DataSet();
ds.Tables.Add(dt);
int jValue = oSheet.UsedRange.Cells.Columns.Count;
int iValue = oSheet.UsedRange.Cells.Rows.Count;
for (int j = 1; j <= jValue; j++)
{
dt.Columns.Add("column" + j, Type.GetType("System.String"));
}
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);
}
}