Embed object in Excel programmatically

别说谁变了你拦得住时间么 提交于 2019-12-14 00:33:35

问题


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!


回答1:


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



来源:https://stackoverflow.com/questions/17860447/embed-object-in-excel-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!