/// <summary> 
/// 将图片插入到指定的单元格位置,并设置图片的宽度和高度。
/// 注意:图片必须是绝对物理路径    
/// </summary>
/// <param name="objSheet">工作表对象</param>
/// <param name="range">单元格名称,例如:B4</param>  
/// <param name="picturePath">要插入图片的绝对路径。</param>  
/// <param name="pictureWidth">插入后,图片在Excel中显示的宽度。</param>    
/// <param name="pictureHeight">插入后,图片在Excel中显示的高度。</param>   
/// <param name="isChangeCellSize">是否按图片尺寸设置单元格大小</param>
/// <param name="offsetX">位置水平位移值</param>
/// <param name="offsetY">位置垂直位移值</param>
public static void InsertPic(Worksheet objSheet, Range range, string picturePath, float pictureWidth, float pictureHeight, bool isChangeCellSize, Single offsetX, Single offsetY)
{
    object objOpt = System.Reflection.Missing.Value;
    range.Select();
    float picLeft,picTop;
    picLeft = Convert.ToSingle(range.Left) + offsetx;
    picTop = Convert.ToSingle(range.Top) + offsetY;
    //Analysis size of pic and make it suit to the cell
    //封装GDI+位图,此位图由图形图像及其属性的像素数据组成。
    Bitmap bitmap = new Bitmap(picturePath);
    float picActualHeight = Convert.ToSingle(bitmap.Size.Height.ToString());
    float picActualWidth = Convert.ToSingle(bitmap.Size.Width.ToString());
    float heightScale = picActualHeight / pictureHeight;
    float widthScale = picActualWidth / pictureWidth;
    if(heightScale > widthScale) //use the larger scale
    {
        picActualHeight = pictureHeight - 2;
        picActualWidth = picActualWidth / heightScale - 2;
    }
    else
    {
        picActualHeight = picActualHeight / widthScale - 2;
        picActualWidth = pictureWidth - 2;
    }
    bitmap.Dispose();
    //参数含义:
    //图片路径
    //是否链接到文件
    //图片插入时是否随文档一起保存
    //图片在文档中的坐标位置(单位:points)
    //图片显示的宽度和高度(单位:points)
    objSheet.Shapes.AddPicture(picturePath, Microsoft.Office.Core.MsoTriState.msoFalse,  Microsoft.Office.Core.MsoTriState.msoTrue, picLeft, picTop, picActualWidth, picActualHeight);
    if (isChangeCellSize)
    {
        range.ColumnWidth = pictureWidth * 0.168;
        range.RowHeight = pictureHeight;
    }
}

 

posted on 2013-02-01 16:13  风扬剪影  阅读(822)  评论(0编辑  收藏  举报