I try to save range of cells from excel file to a picture. I used the CopyPicture method from the interop.excel api so the picture sould be on clipboard. When i press ctrl+v on a word document for example, i get the picture but i can't success to get it with code. The returned data from the GetImageFromClipBoard method is null.
public void SaveAsImage()
{
var usedRange = ws.UsedRange;
int startRow = usedRange.Row;
int endRow = startRow + usedRange.Rows.Count - 1;
int startColumn = usedRange.Column;
int endColumn = startColumn + usedRange.Columns.Count - 1;
Xl.Range rng = wb.ActiveSheet.Range[ws.Cells[1, 1],
ws.Cells[endRow, endColumn]];
rng.CopyPicture(Xl.XlPictureAppearance.xlScreen,
Xl.XlCopyPictureFormat.xlBitmap);
Image image = GetImageFromClipBoard();
image.Save("image.bmp", System.Drawing.Imaging.ImageFormat.Bmp);
}
[STAThread]
private Image GetImageFromClipBoard()
{
IDataObject clipboardData = Clipboard.GetDataObject();
Exception threadEx = null;
Thread staThread = new Thread(
delegate ()
{
try
{
clipboardData = Clipboard.GetDataObject();
}
catch (Exception ex)
{
threadEx = ex;
}
});
staThread.SetApartmentState(ApartmentState.STA);
staThread.Start();
staThread.Join();
return (Bitmap)clipboardData.GetData(DataFormats.Bitmap);
}