How can I avoid this Exception when copying a sele

2019-07-29 00:44发布

In another question I asked how to export an excel worksheet as image. Well, the logic behind the answer is OK. But I'm geting an Exception when calling CopyPicture (System.Runtime.InteropServices.COMException).

var a = new Microsoft.Office.Interop.Excel.Application();
Workbook w = a.Workbooks.Open(@"C:\scratch\blueyellow.xlsx");
Worksheet ws = w.Sheets["StatusR"];
ws.Protect(Contents: false);

Thread.Sleep(3000); // Fix (sometimes)
Range r = ws.Range["B4:P24"];
r.CopyPicture(XlPictureAppearance.xlScreen, XlCopyPictureFormat.xlBitmap); // <--- Exception
var data = Clipboard.GetDataObject();
data.GetDataPresent(DataFormats.Bitmap);
Image image = (Image)data.GetData(DataFormats.Bitmap, true);
image.Save(@"C:\scratch\informe_by.png", System.Drawing.Imaging.ImageFormat.Png);
w.Close(SaveChanges: false);
a.Quit(); 

I have put a Thread.Sleep() line before to solve this issue. It works most of the time. But would like it to work always without extrange behaviors.

I'm using Windows 8 Profesional 64 bits, Office 2013 64 bits and .Net 4

What can be wrong?

标签: c# excel
1条回答
对你真心纯属浪费
2楼-- · 2019-07-29 01:32

After unsuccesful research, I ended up with this inelegant solution:

var errorCounter = 0;
var copyDone = false;
do {
   try {
      r.CopyPicture(XlPictureAppearance.xlScreen, XlCopyPictureFormat.xlBitmap);
      copyDone = true;
   } catch {
      ++errorCounter;
} while (!copyDone && errorCounter <= 100);

if (errorCounter == 100) throw new ApplicationException("Unable to copy the selected range.");

I hope this help others.

查看更多
登录 后发表回答