How to insert a picture in to Excel from C# app?
Add the following references:
Microsoft.Office.Interop.Excel
from the .Net tabMicrosoft 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 !");
}
You need to add the Microsoft excel library.
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"));
}