How to Align a Picture within a Cell in C#, VB.NET

By default, when we insert an image to a cell, the image automatically be placed at top left corner. If there are some text in the same cell, then the text will be covered by the image. To avoid the problem, we need to vertically or horizontally align the picture. This article focuses on how to align a picture within a cell using Spire.XLS with C#, VB.NET.

Code Snippet:

Step 1: Create an object of Workbook and get the first worksheet.

Workbook wb = new Workbook();
Worksheet sheet = wb.Worksheets[0];

Step 2: Insert an image to the specific cell using Pictures.Add(int topRow, int leftColumn, string filename) method.

string picPath = @"C:\Users\Administrator\Desktop\scenery.jpg";
ExcelPicture picture = sheet.Pictures.Add(1, 1, picPath);

Step 3: Adjust the column width and row height so that the cell can contain the picture.

sheet.Columns[0].ColumnWidth = 50;
sheet.Rows[0].RowHeight = 150;

Step 4: Vertically and horizontally align the image by setting values for LeftColumnOffset and TopRowOffset properties.

picture.LeftColumnOffset = 100;
picture.TopRowOffset = 25;

Step 5: Save the file.

wb.SaveToFile("AlignPicture.xlsx", ExcelVersion.Version2013);

Output:

How to Align a Picture within a Cell in C#, VB.NET

Full Code:

[C#]
Workbook wb = new Workbook();
Worksheet sheet = wb.Worksheets[0];

sheet.Range["A1"].Text = "Align Picture Within A Cell:";
sheet.Range["A1"].Style.VerticalAlignment = VerticalAlignType.Top;

string picPath = @"C:\Users\Administrator\Desktop\scenery.jpg";
ExcelPicture picture = sheet.Pictures.Add(1, 1, picPath);

sheet.Columns[0].ColumnWidth = 50;
sheet.Rows[0].RowHeight = 150;

picture.LeftColumnOffset =100;
picture.TopRowOffset = 25;

wb.SaveToFile("AlignPicture.xlsx", ExcelVersion.Version2013);
[VB.NET]
Dim wb As New Workbook()
Dim sheet As Worksheet = wb.Worksheets(0)

sheet.Range("A1").Text = "Align Picture Within A Cell:"
sheet.Range("A1").Style.VerticalAlignment = VerticalAlignType.Top

Dim picPath As String = "C:\Users\Administrator\Desktop\scenery.jpg"
Dim picture As ExcelPicture = sheet.Pictures.Add(1, 1, picPath)

sheet.Columns(0).ColumnWidth = 50
sheet.Rows(0).RowHeight = 150

picture.LeftColumnOffset = 100
picture.TopRowOffset = 25

wb.SaveToFile("AlignPicture.xlsx", ExcelVersion.Version2013)