Home » excel » c# – Embed object in Excel programmatically

c# – Embed object in Excel programmatically

Posted by: admin April 23, 2020 Leave a comment

Questions:

I’ve tried several libraries, including EPPlus, NPOI and they can insert images, but i couldn’t find how to insert objects(pdf’s, text files, images) as files. Is there any way or library to do that in .NET?
Thanks!

How to&Answers:

Using this code I was able to embed a PDF file, a txt file , and a png file into Excel using C#.

    public static class ExcelReaderFunctions {

        public static void ExcelInsertOLE(string path) {

            Microsoft.Office.Interop.Excel.Application excel = new Application();
            excel.Workbooks.Add();            
            Microsoft.Office.Interop.Excel.Workbook workBook = excel.ActiveWorkbook;
            Microsoft.Office.Interop.Excel.Worksheet sheet = workBook.ActiveSheet;

            OLEObjects oleObjects =    (Microsoft.Office.Interop.Excel.OLEObjects)
                sheet.OLEObjects(Type.Missing);            

            oleObjects.Add(
                Type.Missing,   // ClassType
                path,           // Filename
                true,           // Link
                false,          // DisplayAsIcon
                Type.Missing,   // IconFileName
                Type.Missing,   // IconIndex
                Type.Missing,   // IconLabel
                Type.Missing,   // Left
                Type.Missing,   // Top
                Type.Missing,   // Width
                Type.Missing    // Height
            );

            excel.Visible = true;
            workBook.Close(true);
            excel.Quit();
        }
    }

Then you call the function with the path of the object you want to embed:

    ExcelReaderFunctions.ExcelInsertOLE(@"c:\my.pdf");
    ExcelReaderFunctions.ExcelInsertOLE(@"c:\my.txt");
    ExcelReaderFunctions.ExcelInsertOLE(@"c:\my.png");

Resource:

MSDN OLEDBObjects.Add Method