简体   繁体   中英

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#. 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. The ColumnWidth property receives the number of points and not centimeters. 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.

How can I solve this case?

Thank you,

The column width in Excel is specified in "Characters", not "Points". 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.

In order to specify the column width in cm, you need to first convert cm to points using the following function:

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). (For columns whose width is greater than 'x' points)

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). (For columns whose width is lesser than 'x' points)

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).

Note: In the above code, xl : Excel application object ws : Worksheet object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM