Tuesday, January 22, 2008

Programmatically embed a picture inside an Excel Sheet

he following code uses EXCEL automation to open an existing workbook and embed an image.

In order to run this code, please add a COM reference to Microsoft Excel 11.0 Object Library in your project


object missingParam = Type.Missing;
ApplicationClass objExcel = new ApplicationClass();
Workbook workbook = objExcel.Workbooks.Open(@"c:\book1.xls", missingParam, missingParam, missingParam, missingParam,
missingParam, missingParam, missingParam, missingParam,
missingParam, missingParam, missingParam, missingParam,
missingParam, missingParam);
Worksheet worksheet = (Worksheet) workbook.Worksheets["Sheet1"];
Range cellRange = worksheet.get_Range("A2", "A2");
string picFilePath = @"d:\sailboat.jpg";
Image picObject = Image.FromFile(picFilePath);
System.Windows.Forms.Clipboard.SetDataObject(picObject, true);
worksheet.Paste(cellRange, picObject);
workbook.Save();
System.Windows.Forms.Clipboard.Clear();
objExcel.Quit();

1 comment:

Maverick27 said...

Anand

How do i add a COM reference to Microsoft Excel 11.0 Object Library in your project ?

DC