13

I am trying to insert a picture into Excel Spread Sheet using my C# application.

I have used the following as my source. http://csharp.net-informations.com/excel/csharp-insert-picture-excel.htm

This whole line is underlined in blue.

 xlWorkSheet.Shapes.AddPicture("C:\\pic.JPG", Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, 50, 50, 300, 45); 

My Code:

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();
    xlWorkBook = xlApp.Workbooks.Add(misValue);
    xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

    //xlWorkSheet.SetBackgroundPicture("C:/Users/Shaun/Documents/Visual Studio 2010/Projects/TestXMLToEXCEL/TestXMLToEXCEL/bin/Debugpic.JPG"); //

    //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:\\pic.JPG", Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, 50, 50, 300, 45); //C:\\csharp-xl-picture.JPG

     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();
    }
}

Error messages:

The best overloaded method match for 'Microsoft.Office.Interop.Excel.Shapes.AddPicture(string, Microsoft.Office.Core.MsoTriState, Microsoft.Office.Core.MsoTriState, float, float, float, float)' has some invalid arguments

The type 'Microsoft.Office.Core.MsoTriState' is defined in an assembly that is not referenced. You must add a reference to assembly 'office, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c'.

Argument 2: cannot convert from 'Microsoft.Office.Core.MsoTriState [c:\users\shaun\documents\visual studio 2010\Projects\TestXMLToEXCEL\TestXMLToEXCEL\CreateSpreadSheet.cs]' to 'Microsoft.Office.Core.MsoTriState'

Argument 3: cannot convert from 'Microsoft.Office.Core.MsoTriState [c:\users\shaun\documents\visual studio 2010\Projects\TestXMLToEXCEL\TestXMLToEXCEL\CreateSpreadSheet.cs]' to 'Microsoft.Office.Core.MsoTriState'


My References:

using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.Office.Core;
using Microsoft.Office;
using System.Xml;
B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862
Pomster
  • 14,567
  • 55
  • 128
  • 204
  • Just add reference to `Microsoft.Office.Core.dll`. Error clearly says that: `The type 'Microsoft.Office.Core.MsoTriState' is defined in an assembly that is not referenced` – Renatas M. Jul 30 '12 at 07:19
  • seems you referencing one version, but it uses different. Have you added reference to v.12 dll? – Renatas M. Jul 30 '12 at 07:36
  • No its seems i'm am referencing interop.Microsoft.Office.Core.dll and its versions is 2.4.0.0, Where would i find, v.12 Microsoft.Office.Core newest version? – Pomster Jul 30 '12 at 07:45

7 Answers7

21

Add the following references:

  • Microsoft.Office.Interop.Excel from the .Net tab
  • Microsoft Office 14.0 Object Library from the COM tab

Add the following using statements:

using Microsoft.Office.Core;
using Excel = Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;

And then here is your method (slightly altered):

private void BtnWriteSpreedSheetClick(object sender, EventArgs e)
{
    var xlApp = new Excel.Application();
    Excel.Workbook xlWorkBook = xlApp.Workbooks.Add();
    Excel.Worksheet xlWorkSheet = xlWorkBook.Sheets[1];

    xlWorkSheet.Cells[1, 1] = "http://csharp.net-informations.com";
    xlWorkSheet.Cells[2, 1] = "Adding picture in Excel File";

    xlWorkSheet.Shapes.AddPicture(@"C:\pic.JPG", MsoTriState.msoFalse, MsoTriState.msoCTrue, 50, 50, 300, 45);

    xlWorkBook.SaveAs("csharp.net-informations.xls", Excel.XlFileFormat.xlWorkbookNormal);
    xlWorkBook.Close(true);
    xlApp.Quit();

    Marshal.ReleaseComObject(xlApp);

    MessageBox.Show("File created !");
}
JMK
  • 27,273
  • 52
  • 163
  • 280
  • 1
    In my application images insertion is a bottleneck. Each generated XLSX file has at least 300-400 images. The current solution calls worksheet.Shapes.AddPicture() method as many times as the number of pictures. This is really slow. Is there a workaround to make it faster? – mr_esp Oct 13 '13 at 19:08
  • Can a location on the internet, rather than a local file, be used as the first arg to AddPicture(), such as: "http://www.bla.com/someImage.png"? – B. Clay Shannon-B. Crow Raven Feb 05 '16 at 19:59
2

You need to add the Microsoft excel library.

enter image description here

Pomster
  • 14,567
  • 55
  • 128
  • 204
2

As an alternative you could use one of the Open Xml libraries such as EPPlus to do this.

In my opinion, EPPlus is much easier & more intuative than Excel interop with no need to manually release resources. It also has the added benefit that it can be performed on a machine without Excel installed.

Something as simple as this with EPPlus works well:

using (var excel = new ExcelPackage())
{
    var wks = excel.Workbook.Worksheets.Add("Sheet1");
    wks.Cells[1, 1].Value = "Adding picture below:";
    var pic = wks.Drawings.AddPicture("MyPhoto", new FileInfo("image.png"));
    pic.SetPosition(2, 0, 1, 0);
    excel.SaveAs(new FileInfo("outputfile.xlsx"));
}
Stewart_R
  • 13,764
  • 11
  • 60
  • 106
1

Just add

using Microsoft.Office.Interop.Excel;
using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.Office.Core;

to your code and rebuild your solution before your run again.

Marijn
  • 10,367
  • 5
  • 59
  • 80
writeToBhuwan
  • 3,233
  • 11
  • 39
  • 67
1

I am using this code with Microsoft.Office.Interop.Excel v 14.0:

xlWorksheet.Shapes.AddPicture(@"c:\pics\logosmall.jpg", Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, 0, 0, 185, 42);

And have got images (jpg and png) in my excel sheets.

brodoll
  • 1,851
  • 5
  • 22
  • 25
Kitemark76
  • 101
  • 1
  • 8
0
    private void Button1_Click(object sender, EventArgs e)
    {

        Microsoft.Office.Interop.Excel._Application application = new Microsoft.Office.Interop.Excel.Application();
        Microsoft.Office.Interop.Excel._Workbook workbook = application.Workbooks.Add(Type.Missing);
        Microsoft.Office.Interop.Excel._Worksheet worksheet = null;

        SaveFileDialog saveDialog = new SaveFileDialog();
        saveDialog.FileName = "ImageToExcel.xlsx";
        if (saveDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            try
            {
                worksheet = workbook.ActiveSheet;
                worksheet.Name = "Image to Excel";
                string imageNetworkLocation = "\\\\192.168.240.110\\images\\image.png";
                worksheet.Shapes.AddPicture(imageNetworkLocation, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, 0, 0, 170, 85);
                workbook.SaveAs(saveDialog.FileName);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            finally
            {
                application.Quit();
                workbook = null;
                application = null;

            }
        }

        else
            try
            {
                workbook.Close(0);
                application.Quit();
                workbook = null;
                application = null;
                System.Runtime.InteropServices.Marshal.ReleaseComObject(application);
            }
            catch (System.Exception ex) 
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
    }
0

If you want to add image to excel sheet from the resources you can use the following code from this answer: https://stackoverflow.com/a/16979892/8712569

    internal static void GenerateExcel()
    {
        Application excel;
        Workbook excelworkBook;
        Worksheet excelSheet;

        // Start Excel and get Application object.  
        excel = new Application();
        // for making Excel visible  
        excel.Visible = false;
        excel.DisplayAlerts = false;
        // Creating a new Workbook  
        excelworkBook = excel.Workbooks.Add(Type.Missing);
        // Get the active sheet  
        excelSheet = (Worksheet)excelworkBook.ActiveSheet;
        excelSheet.Name = "SheetWithImage";

        System.Drawing.Bitmap pic = Properties.Resources.my_logo;
        System.Windows.Forms.Clipboard.SetImage(pic);
        Range position = (Range)excelSheet.Cells[2, 2];
        excelSheet.Paste(position); //copy the clipboard to the given position

        excelworkBook.SaveAs("MyExcelFile.xlsx", XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing,
            false, false, XlSaveAsAccessMode.xlNoChange,
            Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
        excelworkBook.Close();
        excel.Quit();
    }
Tahirhan
  • 352
  • 1
  • 7
  • 15