单元格中的Excel图像

本文关键字:图像 Excel 单元格 | 更新日期: 2023-09-27 18:08:26

如何将图像(类型为image)插入Excel工作表中的特定单元格

taperSheet = (Microsoft.Office.Interop.Excel.Worksheet)excelSheets.get_Item("Taper");
Microsoft.Office.Interop.Excel.Range cell = GetMyPictureCELL(taperSheet);
Image myImage = new Image();
RenderTargetBitmap bmp;
bmp = new RenderTargetBitmap((int)this.Width, (int)this.Height, 96, 96, PixelFormats.Pbgra32);
bmp.Render(myViewPort);
myImage.Source = bmp;
myImage.Stretch = Stretch.Uniform;

现在呢?我希望

cell.Add(myImage)

但我认为这并不那么容易。

Stefan

谢谢你的输入doitgood

下面的代码为我工作

在我的情况下,我的图像源是一个viewport (myViewPort)图像的位置由cell

决定。
try
{
    Image myImage = new Image();
    RenderTargetBitmap bmp;
    PngBitmapEncoder encoder;
    string fileName;
    System.IO.Stream stream;
    object missing = System.Reflection.Missing.Value; 
    Microsoft.Office.Interop.Excel.Picture pic = null;
    Microsoft.Office.Interop.Excel.Pictures p = null;
    bmp = new RenderTargetBitmap((int)this.Width, (int)this.Height, 96, 96, PixelFormats.Pbgra32);
    bmp.Render(myViewPort);
    myImage.Source = bmp;
    myImage.Stretch = Stretch.Uniform;
    fileName = System.IO.Path.GetTempFileName();
    stream = System.IO.File.OpenWrite(fileName);
    encoder = new PngBitmapEncoder();
    encoder.Frames.Add(BitmapFrame.Create(bmp));
    encoder.Save(stream);
    stream.Close();
    p = taperSheet.Pictures(missing) as Microsoft.Office.Interop.Excel.Pictures; 
    pic = p.Insert(fileName, missing); 
    pic.Left = cell.Left;
    pic.Top = cell.Top;
}
catch { }

单元格中的Excel图像

试试这个:

object missing = System.Reflection.Missing.Value;
Excel.Range picPosition = GetPicturePosition(); // retrieve the range for picture insert
Excel.Pictures p = yourWorksheet.Pictures(missing) as Excel.Pictures;
Excel.Picture pic = null;
pic = p.Insert(yourImageFilePath, missing);
pic.Left = Convert.ToDouble(picPosition .Left);
pic.Top = Convert.ToDouble(picPosition .Top);
pic.Placement = // Can be any of Excel.XlPlacement.XYZ value

别忘了释放所有的东西!

或者试试这个:

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);
}
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;
    }
}