I am trying to add a photo to a Excel Spread sheet but keep getting the following error?
Error 1 Interop type 'Microsoft.Office.Interop.Excel.ApplicationClass' cannot be embedded. Use the applicable interface instead.
ApplicationClass(); is underlined in red in the line of code below:
xlApp = new Excel.ApplicationClass();
Could Some on please tel me how i could fix this?
using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.Office.Core;
private void btnWriteSpreedSheet_Click(object sender, EventArgs e)
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.ApplicationClass(); //This is where the problem is??????
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
//add some text
xlWorkSheet.Cells[1, 1] = "http://csharp.net-informations.com";
xlWorkSheet.Cells[2, 1] = "Adding picture in Excel File";
xlWorkSheet.Shapes.AddPicture("C:\\csharp-xl-picture.JPG", Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, 50, 50, 300, 45);
xlWorkBook.SaveAs("csharp.net-informations.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlApp);
releaseObject(xlWorkBook);
releaseObject(xlWorkSheet);
MessageBox.Show ("File created !");
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Unable to release the Object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
}
In your Project, expand the "References", find the Microsoft Office Interop reference. Right click it and select properties, and change "Embed Interop Types" to false
.
As explained in a MSDN blog post, instead of disabling "Embed Interop Types" you can also change
xlApp = new Excel.ApplicationClass();
into
xlApp = new Excel.Application();
Although Excel.Application
is an interface, we can instantiate it because it is decorated with a CoClass attribute, as explained in this other SO answer: https://stackoverflow.com/a/11039870/501196
Using this approach (Embed Interop Types = true) has the advantage that you will need to deploy less files with your project, and the embedded types will only contain the methods and types that your application is actually using. When you use external interop assemblies, you are importing there all the types and methods exposed by the referenced library.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With