Pasting Image from Excel 2003 Clipboard

99封情书 提交于 2019-12-02 08:23:19

I've found the solution.

Apparently Excel 2007 does not copy the image to the clipboard in the same file format. I iterated through Clipboard.GetDataObject().GetFormats() and found that it contained the following:

Office Drawing Shape Format MetaFilePict EnhancedMetafile PNG+Office Art JFIF+Office Art GIF+Office Art PNG JFIF GIF ActiveClipboard

To get this to work, I've added a second codeblock to my code with the following:

        if (Clipboard.GetImage() != null) //Excel 2007
        {
            pictureBox1.Width = Clipboard.GetImage().Width;
            pictureBox1.Height = Clipboard.GetImage().Height;
            pictureBox1.Image = Clipboard.GetImage();
            //...
        }
        else if(Clipboard.GetDataObject().GetDataPresent("PNG")) //Excel 2003
        {
            Clipboard.GetDataObject().GetFormats()
            IDataObject data = Clipboard.GetDataObject();
            MemoryStream ms = (MemoryStream)data.GetData("PNG");

            pictureBox1.Width = Image.FromStream(ms).Width;
            pictureBox1.Height = Image.FromStream(ms).Height;
            pictureBox1.Image = Image.FromStream(ms);
            //...
        }

And it works.

SpreadsheetGear for .NET can open Excel workbooks and get images from ranges of cells or from charts as demonstrated by these examples (these examples are for ASP.NET but it works just as well with WinForms apps, console apps, etc...). SpreadsheetGear does not rely on Excel so it will work with Excel 2003 installed, Excel 2007 installed or no Excel installed.

You can download a free trial here.

Disclaimer: I own SpreadsheetGear LLC

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