如何在excel中对齐图像

时间:2017-05-02 10:10:41

标签: c# excel winforms interop

我使用以下代码在excel单元格中插入图像,但结果并不像预期的那样

bitmap[] ImageArray = GetImageArray();
bitmap currvalue = null;
System.Windows.Forms.Clipboard.SetDataObject(ImageArray[0], true);
currvalue = ImageArray[0];

currentRange.Cells.HorizontalAlignment =Excel.XlHAlign.xlHAlignCenterAcrossSelection; 
currentRange.Cells.VerticalAlignment = Excel.XlHAlign.xlHAlignCenter;

excelWorkSheet.Paste(currentRange.Cells, currvalue);
excelWorkSheet.Columns.AutoFit();

this is output

我不能使用objSheet.Shapes.AddPicture();

我希望图像中心对齐

1 个答案:

答案 0 :(得分:1)

在粘贴到excel seheet之后,需要通过代码调整单元格中图像的位置。如下所示,HTH

excelWorkSheet.Paste(currentRange.Cells, currvalue);

foreach (var shp in excelWorkSheet.Shapes)
{
    if (shp.TopLeftCell.Address != currentRange.Address)
        continue;
    shp.Left = shp.TopLeftCell.Left + (shp.TopLeftCell.Width - shp.Width) / 2;
    shp.Top = shp.TopLeftCell.Top + (shp.TopLeftCell.Height - shp.Height) / 2;
    break;
 }