方法一:
/// 将图片插入到指定的单元格位置,并设置图片的宽度和高度。
/// 注意:图片必须是绝对物理路径
/// </summary>
/// <param name="RangeName">单元格名称,例如:B4</param>
/// <param name="PicturePath">要插入图片的绝对路径。</param>
public void InsertPicture(string RangeName, Excel._Worksheet sheet, string PicturePath)
{
Excel.Range rng = (Excel.Range)sheet.get_Range(RangeName, Type.Missing);
rng.Select();
float PicLeft, PicTop, PicWidth, PicHeight; //距离左边距离,顶部距离,图片宽度、高度
PicTop = Convert.ToSingle(rng.Top) ;
PicWidth = Convert.ToSingle(rng.MergeArea.Width);
PicHeight = Convert.ToSingle(rng.Height);
PicWidth = Convert.ToSingle(rng.Width);
PicLeft = Convert.ToSingle(rng.Left);//+ (Convert.ToSingle(rng.MergeArea.Width) - PicWidth) / 2;
try
{
Excel.Pictures pics = (Excel.Pictures)sheet.Pictures(Type.Missing);
pics.Insert(PicturePath, Type.Missing);
pics.Left = (double)rng.Left;
pics.Top = (double)rng.Top;
pics.Width = (double)rng.Width;
pics.Height = (double)rng.Height;
}
catch
{
}
//sheet.Shapes.AddPicture(PicturePath, Microsoft.Office.Core.MsoTriState.msoFalse,
// Microsoft.Office.Core.MsoTriState.msoTrue, PicLeft, PicTop, PicWidth, PicHeight);
}
如果是要在某个区域插入,改区域没有命名的话,直接传入选中区域
Cell1 = SourceSheet.Cells[第几行, 第几列];
Cell2 = SourceSheet.Cells[Row , Column];
SourceRange = SourceSheet.get_Range(Cell1, Cell2);
然后把上面的这句去掉 Excel.Range rng = (Excel.Range)sheet.get_Range(RangeName, Type.Missing);
把rng换成SourceRange
方法二:
sheet.Shapes.AddPicture(。。。。。)
/// 将图片插入到指定的单元格位置,并设置图片的宽度和高度。
/// 注意:图片必须是绝对物理路径
/// </summary>
/// <param name="rng">Excel单元格选中的区域</param>
/// <param name="PicturePath">要插入图片的绝对路径。</param>
public void InsertPicture(Excel.Range rng, Excel._Worksheet sheet, string PicturePath)
{
rng.Select();
float PicLeft, PicTop, PicWidth, PicHeight;
try
{
PicLeft = Convert.ToSingle(rng.Left);
PicTop = Convert.ToSingle(rng.Top);
PicWidth = Convert.ToSingle(rng.Width);
PicHeight = Convert.ToSingle(rng.Height);
//参数含义:
//图片路径
//是否链接到文件
//图片插入时是否随文档一起保存
//图片在文档中的坐标位置 坐标
//图片显示的宽度和高度
sheet.Shapes.AddPicture(PicturePath, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoTrue, PicLeft, PicTop, PicWidth, PicHeight);
}
catch(Exception ex)
{
MessageBox.Show("错误:" + ex.Message);
}
}