Home » excel » c# – Excel Interop get width in pixels of text inside cell

c# – Excel Interop get width in pixels of text inside cell

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have a wide merged cell showing the title of the sheet. I also have a colored Textbox that I would like to position immediately to the right of the text in the merged cell.

The width of the title is variable so I have used a very wide merged cell.

sheet.Range["A2"].Value = title;
//Red Square
sheet.Shapes.Item("redSquare").Left += 0; // Position sheet.Range["A2"].TextWidth ???

Is there a property I can access on Range that will give me the actual text width in pixels of the text in merged cell?

How to&Answers:

As far as I know, there isn’t anything in Interop that will tell you the width of text in pixels, but you can do it with the following. It seems to return a value reasonably similar to the column widths that Excel sets based on the same fonts.

Excel.Range xlRange = sheet.get_Range("A2");
Excel.Font xlFont = xlRange.Font;
string fontName = xlFont.Name;
double fontSize = xlFont.Size;
Font font = new Font(fontName, (float)fontSize);
float width = Graphics.FromImage(new Bitmap(1, 1)).MeasureString(title, font).Width;

You might need to add a few pixels here and there to make sure your textbox clears the end of the text, but I think it’s about as accurate as you’re going to get.