开发人员可以快速利用
Aspose.Cells提供的API为单元格添加图片,并且可以完全控制添加图片的位置,总的来说添加图片到Excel单元格里仅需要几句代码就可以实现,可以为添加的图片设置绝对位置,也可以按照相应比例来设置位置。控件提供了worksheet.Pictures.Add()方法来添加图片,该函数包含了三个变量,第一个变量表示行索引,第二个变量表示列索引,第三个变量表示图片文件名(包含路径)。具体的实现方法可以参考下面的部分代码:
1.添加一个图片到Excel单元格里
//Instantiating a Workbook object
Workbook workbook = new Workbook();
//Adding a new worksheet to the Workbook object
int sheetIndex = workbook.Worksheets.Add();
//Obtaining the reference of the newly added worksheet by passing its sheet index
Worksheet worksheet = workbook.Worksheets[sheetIndex];
//Adding a picture at the location of a cell whose row and column indices
//are 5 in the worksheet. It is "F6" cell
worksheet.Pictures.Add(5, 5, "C:\\image.gif");
//Saving the Excel file
workbook.Save("c:\\book1.xls");
2.添加一个图片到Excel单元格里,并设置相应的比例位置,这个比例是根据单元格行高和列宽来的
//Instantiating a Workbook object
Workbook workbook = new Workbook();
//Adding a new worksheet to the Workbook object
int sheetIndex = workbook.Worksheets.Add();
//Obtaining the reference of the newly added worksheet by passing its sheet index
Worksheet worksheet = workbook.Worksheets[sheetIndex];
//Adding a picture at the location of a cell whose row and column indices
//are 5 in the worksheet. It is "F6" cell
int pictureIndex = worksheet.Pictures.Add(5, 5, "C:\\image.gif");
//Accessing the newly added picture
Aspose.Cells.Drawing.Picture picture = worksheet.Pictures[pictureIndex];
//Positioning the picture proportional to row height and colum width
picture.UpperDeltaX = 200;
picture.UpperDeltaY = 200;
//Saving the Excel file
workbook.Save("C:\\book1.xls");
3.使用绝对位置为单元格添加图片
//Instantiating a Workbook object
Workbook workbook = new Workbook();
//Adding a new worksheet to the Workbook object
int sheetIndex = workbook.Worksheets.Add();
//Obtaining the reference of the newly added worksheet by passing its sheet index
Worksheet worksheet = workbook.Worksheets[sheetIndex];
//Adding a picture at the location of a cell whose row and column indices
//are 5 in the worksheet. It is "F6" cell
int pictureIndex = worksheet.Pictures.Add(5, 5, "C:\\image.gif");
//Accessing the newly added picture
Aspose.Cells.Drawing.Picture picture = worksheet.Pictures[pictureIndex];
//Absolute positioning of the picture in unit of pixels
picture.Left = 60;
picture.Top = 10;
//Saving the Excel file
workbook.Save("C:\\book1.xls");