为Excel工作表添加图片时,我们常会重新调整图片的大小和位置来让图片和整个文档内容协调并美观。本文将介绍如何使用Spire.XLS 来设置Excel 工作表中图片的大小和位置。
添加图片到新的Excel文档中时,设置位置和大小:
C#
//加载一个workbook实例并获取worksheet
Workbook workbook = new Workbook();
Worksheet sheet = workbook.Worksheets[0];
//添加第一张图片
ExcelPicture picture = sheet.Pictures.Add(1, 1, "logo.png");
//设置图片大小
picture.Width = 150;
picture.Height = 150;
//设置图片位置
picture.Left = 20;
picture.Top = 100;
//添加第二张图片并设置大小和位置
ExcelPicture picture2 = sheet.Pictures.Add(4, 1, "xls.png");
picture2.Width = 150;
picture2.Height = 150;
picture2.Left = 20;
picture2.Top = 300;
//保存文档
workbook.SaveToFile("Output.xlsx", FileFormat.Version2013);
VB.NET
'加载一个workbook实例并获取worksheet
Dim workbook As New Workbook()
Dim sheet As Worksheet = workbook.Worksheets(0)
'添加第一张图片
Dim picture As ExcelPicture = sheet.Pictures.Add(1, 1, "logo.png")
'设置图片大小
picture.Width = 150
picture.Height = 150
'设置图片位置
picture.Left = 20
picture.Top = 100
'添加第二张图片并设置大小和位置
Dim picture2 As ExcelPicture = sheet.Pictures.Add(4, 1, "xls.png")
picture2.Width = 150
picture2.Height = 150
picture2.Left = 20
picture2.Top = 300
'保存文档
workbook.SaveToFile("Output.xlsx", FileFormat.Version2013)
调整Excel文档中已有的图片位置和大小:
C#
//加载含有图片的Excel文档
Workbook workbook = new Workbook();
workbook.LoadFromFile("Output.xlsx");
//获取第一个sheet
Worksheet sheet = workbook.Worksheets[0];
//获取第一张图片
ExcelPicture picture = sheet.Pictures[0];
//设置图片大小
picture.Width = 75;
picture.Height = 75;
//设置图片位置
picture.Left = 200;
picture.Top = 300;
//保存文档
workbook.SaveToFile("ResetExcelImage.xlsx", FileFormat.Version2013);
VB.NET
'加载含有图片的Excel文档
Dim workbook As New Workbook()
workbook.LoadFromFile("Output.xlsx")
'获取第一个sheet
Dim sheet As Worksheet = workbook.Worksheets(0)
'获取第一张图片
Dim picture As ExcelPicture = sheet.Pictures(0)
'设置图片大小
picture.Width = 75
picture.Height = 75
'设置图片位置
picture.Left = 200
picture.Top = 300
'保存文档
workbook.SaveToFile("ResetExcelImage.xlsx", FileFormat.Version2013)