How to insert a picture in excel from C# App

The following section shows how to insert a picture in an Excel file from C# Application .

In the subsequent C# source code, we will be utilizing the Microsoft Excel 12.0 Object Library to integrate Excel functionalities within our application. As discussed in the preceding section, we have already explored the process of importing the Microsoft Excel 12.0 Object Library into our C# project, thereby equipping us with the necessary tools to seamlessly incorporate Excel features. By employing this library, we can now investigate into the implementation of Excel-related functionalities within our C# application.

Create Excel file from CSharp

To insert a picture in an Excel file using C#, the AddPicture method needs to be invoked. This method requires several parameters to be passed, including the PictureName along with its path, as well as the Left, Top, Width, and Height properties. These parameters determine the positioning and dimensions of the inserted picture within the Excel file. By providing the appropriate values for these parameters, developers can successfully insert pictures into Excel files using C#.

After you execute the C# source code you will get the Excel file like the following picture.

csharp-excel-insert-picture Full Source C#
using System; using System.Windows.Forms; using Excel = Microsoft.Office.Interop.Excel; namespace WindowsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Excel.Application xlApp ; Excel.Workbook xlWorkBook ; Excel.Worksheet xlWorkSheet ; object misValue = System.Reflection.Missing.Value; xlApp = new Excel.Application(); xlWorkBook = xlApp.Workbooks.Add(misValue); xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1); //add some text xlWorkSheet.Cells[1, 1] = "https://net-informations.com/csharp/default.htm"; 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(); } } } }