问题
I have images within an excel file, that I need to manually extract. I have written a program which functions very well for our users with Excel 2007, but will not work with Excel 2003.
Process: User Opens Excel File, Copies Relevant Image to Clipboard User Opens C# Application, Clicks Button Which Gathers Image from Clipboard, and then gathers additional information from the user.
The application code is pretty simple. On button click, the following code is called:
if (Clipboard.GetImage() != null)
{
pictureBox1.Width = Clipboard.GetImage().Width;
pictureBox1.Height = Clipboard.GetImage().Height;
pictureBox1.Image = Clipboard.GetImage();
//...more misc. code...
}
This works flawlessly with Excel 2007, but does not function with Excel 2003.
I have attempted the following debug code, all which fails:
Clipboard.ContainsImage() >> returns false Clipboard.GetDataObject().GetDataPresent(DataFormats.Bitmap) >> false
One thought would be that the Excel 2003 "Office Clipboard" may be interfering? MS PAINT has no issue pasting the image however.
Help?
回答1:
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.
回答2:
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
来源:https://stackoverflow.com/questions/1405756/pasting-image-from-excel-2003-clipboard