I want to select a range in a sheet and paste it into another as an image, using Interop.
It is easy to do using the Excel UI, just right-click the cell then paste special > image.
How to do in excel
I tried to do something similar to this VBA macro, but I could not find any method similar to ActiveSheet.Pictures.Paste.Select
.
Range("C5:U22").Select
Selection.Copy
Range("I4").Select
Sheets("Sheet2").Select
Range("E7").Select
ActiveSheet.Pictures.Paste.Select
I also tried to copy the range and get the clipboard data as an image using range.CopyPicture(XlPictureAppearance.xlScreen, XlCopyPictureFormat.xlBitmap);
, and then save it to a file and copy the file back to Excel. But it did not work as the image file was empty. (I know that the performance of this solution would not be good, but I could not think of anything else.)
range.CopyPicture(XlPictureAppearance.xlScreen, XlCopyPictureFormat.xlBitmap);
string imagePath = Path.Combine(stringTmpDirPath, "image.png");
SaveClipboardImageToFile(imagePath);
private static void SaveClipboardImageToFile(string filePath)
{
BitmapSource image = Clipboard.GetImage();
if (image == null) return;
using (FileStream fileStream = new FileStream(filePath, FileMode.Create))
{
BitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(image));
encoder.Save(fileStream);
}
}
Reference
JANHEK is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.