Excel的互操作得到宽度内细胞的文本像素 [英] Excel Interop get width in pixels of text inside cell
问题描述
我有一个广泛的合并单元格显示表的标题。我也有一个彩色的文本框,我想立刻定位到在合并单元格中的文本的右侧。
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?
推荐答案
据我所知,没有任何东西互操作,将告诉你在像素文本的宽度,但你可以用下面的做到这一点。它似乎返回一个值相当类似,基于相同的字体的Excel套列宽。
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.
这篇关于Excel的互操作得到宽度内细胞的文本像素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!