问题
I insert an image into an Excel range like so:
private System.Drawing.Image _logo;
public ProduceUsageRpt(..., System.Drawing.Image logo)
{
. . .
_logo = logo;
}
. . .
var logoRange = _xlSheet.Range[
_xlSheet.Cells[LOGO_FIRST_ROW, _grandTotalsColumn], _xlSheet.Cells[LOGO_LAST_ROW, _grandTotalsColumn]];
Clipboard.SetDataObject(_logo, true);
_xlSheet.Paste(logoRange, _logo);
Unfortunately, the image is too large for that range (currently row 1 to row 4, column 16). Instead of doing the polite thing and scaling itself down to fit the prescribed bounds, it spills out and over its assigned vertical and horizontal spot.
How can I get the image to scale down and restrict itself to its "box"?
回答1:
I got the answer from adapting one at a related question here.
As long as I make the range large enough, this works:
. . .
var logoRange = _xlSheet.Range[
_xlSheet.Cells[LOGO_FIRST_ROW, _grandTotalsColumn], _xlSheet.Cells[LOGO_LAST_ROW, _grandTotalsColumn+1]];
PlacePicture(_logo, logoRange);
}
// From Jürgen Tschandl
private void PlacePicture(Image picture, Range destination)
{
Worksheet ws = destination.Worksheet;
Clipboard.SetImage(picture);
ws.Paste(destination, false);
Pictures p = ws.Pictures(System.Reflection.Missing.Value) as Pictures;
Picture pic = p.Item(p.Count) as Picture;
ScalePicture(pic, (double)destination.Width, (double)destination.Height);
}
// Also from Jürgen Tschandl
private void ScalePicture(Picture pic, double width, double height)
{
double fX = width / pic.Width;
double fY = height / pic.Height;
double oldH = pic.Height;
if (fX < fY)
{
pic.Width *= fX;
if (pic.Height == oldH) // no change if aspect ratio is locked
pic.Height *= fX;
pic.Top += (height - pic.Height) / 2;
}
else
{
pic.Width *= fY;
if (pic.Height == oldH) // no change if aspect ratio is locked
pic.Height *= fY;
pic.Left += (width - pic.Width) / 2;
}
}
来源:https://stackoverflow.com/questions/35899391/how-can-i-prevent-the-pasted-image-from-overflowing-its-boundaries