[英]How can I set an exact size (in centimeters) for an Excel cell programatically (C#)?
I intend to write some information to Excel from C#. 我打算从C#向Excel写一些信息。 The code I am using is: 我使用的代码是:
var oXL = new Microsoft.Office.Interop.Excel.Application();
oXL.Visible = false;
var oWB = (Microsoft.Office.Interop.Excel._Workbook)(oXL.Workbooks.Add(""));
var oSheet = (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet;
oSheet.Columns.ColumnWidth = 5;
oSheet.Rows.RowHeight = 5;
oSheet.Cells[1, 1] = "Smith";
...
The problem is that I need to set an exact size in centimeters (5) for all the cells. 问题是我需要为所有单元格设置以厘米(5)为单位的精确尺寸。 The ColumnWidth
property receives the number of points and not centimeters. ColumnWidth
属性接收点数而不是厘米。 In various articles I found that 1 point = 0.035cm, meaning that 1cm = 28.57p, but when I pass 5*28.57 for ColumnWidth
and for RowHeight
, Excel's columns are set to 28.58cm and rows are set to 5.04cm. 在各种文章中,我发现1点= 0.035cm,意味着1cm = 28.57p,但是当我为ColumnWidth
和RowHeight
传递5 * 28.57时,Excel的列设置为28.58cm,行设置为5.04cm。
How can I solve this case? 我该如何解决这个案子?
Thank you, 谢谢,
The column width in Excel is specified in "Characters", not "Points". Excel中的列宽在“字符”中指定,而不是“点”。 The default column width is 8.37 "Characters", 1 character being the width of the 1 character of the default font used to display normal text in Excel. 默认列宽为8.37“字符”,1个字符是用于在Excel中显示普通文本的默认字体的1个字符的宽度。
In order to specify the column width in cm, you need to first convert cm to points using the following function: 要以cm为单位指定列宽,您需要先使用以下函数将cm转换为点:
double x = xl.Application.CentimetersToPoints(5);
Then use one loop to repeatedly decrease the column width by 0.1 points until it matches the number of points (x). 然后使用一个循环重复地将列宽减小0.1个点,直到它与点数(x)匹配。 (For columns whose width is greater than 'x' points) (对于宽度大于'x'点的列)
while(ws.Columns.ColumnWidth - 0.1 > points)
{
ws.Columns.ColumnWidth = ws.Columns.ColumnWidth - 0.1;
}
Then use another loop to repeatedly increase the column width by 0.1 points until it matches the number of points (x). 然后使用另一个循环重复地将列宽增加0.1点,直到它与点数(x)匹配。 (For columns whose width is lesser than 'x' points) (对于宽度小于'x'点的列)
while(ws.Columns.ColumnWidth + 0.1 < points)
{
ws.Columns.ColumnWidth = ws.Columns.ColumnWidth + 0.1;
}
The above method takes a few seconds to execute because of the loops. 由于循环,上述方法需要几秒钟才能执行。 However, it achieves the solution (setting column width in cm). 但是,它实现了解决方案(以cm为单位设置列宽)。
Note: In the above code, xl : Excel application object ws : Worksheet object 注意:在上面的代码中,xl:Excel应用程序对象ws:Worksheet对象
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.