时间:2022-02-05 10:50:25 | 栏目:.NET代码 | 点击:次
dll文件获取及引用:
方法1:通过官网下载dll文件包,并解压。解压文件后,将bin文件夹下的Spire.Xls.dll文件引用到C#程序。
方法2:通过Nuget网站获取dll。
C#代码示例
using Spire.Xls; using System.Drawing; namespace InsertImage_XLS { class Program { static void Main(string[] args) { //创建Workbook对象 Workbook workbook = new Workbook(); //获取第一张工作表 Worksheet sheet = workbook.Worksheets[0]; //指定列宽、行高 sheet.Columns[0].ColumnWidth = 50; sheet.Rows[0].RowHeight = 160; //加载图片,添加到指定单元格 ExcelPicture picture = sheet.Pictures.Add(1,1, "tp.png"); //指定图片宽度和高度 picture.Width = 300; picture.Height = 180; //通过LeftColumnOffset和TopRowOffset属性值设置图片在单元格中的横向、纵向对齐 picture.LeftColumnOffset = 75; picture.TopRowOffset = 20; //保存文档 workbook.SaveToFile("result.xlsx", FileFormat.Version2013); System.Diagnostics.Process.Start("result.xlsx"); } } }
图片插入效果:
扩展知识点:
C# 导入图片到Excel单元格
导出Excel功能时需要将数据中含有图片也导出到excel单元格中
public void InsertPicture(string RangeName, string PicturePath, Microsoft.Office.Interop.Excel.Worksheet worksheet) { Microsoft.Office.Interop.Excel.Range m_objRange = worksheet.get_Range(RangeName, Type.Missing); m_objRange.Select(); float PicLeft, PicTop, PicWidth, PicHeight; //距离左边距离,顶部距离,图片宽度、高度 PicTop = Convert.ToSingle(m_objRange.Top); PicWidth = Convert.ToSingle(m_objRange.MergeArea.Width); PicHeight = Convert.ToSingle(m_objRange.Height)-10; PicWidth = Convert.ToSingle(m_objRange.Width)-10; PicLeft = Convert.ToSingle(m_objRange.Left);//+ (Convert.ToSingle(rng.MergeArea.Width) - PicWidth) / 2; try { //worksheet.Shapes.AddPicture(PicturePath, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoTrue, PicLeft, PicTop, PictuteWidth, PictureHeight); worksheet.Shapes.AddPicture(PicturePath, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoTrue, PicLeft, PicTop, 90, 70); } catch { } }