Reputation: 1294
I am using excel interop in creating excel. Now, I have to get the size of a column as basis of what the next column's size would be. I tried the following code:
width = xlWorksheet.Range[xlWorksheet.Cells[1, 4], xlWorksheet.Cells[1, 11]].Width;
xlWorksheet.Columns[5].ColumnWidth = width;
width_of_first_col = xlWorksheet.Range[xlWorksheet.Cells[1, 1], xlWorksheet.Cells[1, 1]].Width;
xlWorksheet.Columns[6].ColumnWidth = width_of_first_col;
The result should be column 4 and column 5 have the same size, as well as column 1 and 6. But this is not true to what the exact result looks like.
What is the best thing to do to set the with of a cell to another cell. Thanks.
Upvotes: 0
Views: 5154
Reputation: 1565
Range.Width
is a read-only property, which give you the width in points.
Range.ColumnWidth
is a read/write property, which gives you the width in what I like to call character units. A character unit represents the width of the character 0
under the font type and size as defined by the Normal
style of the workbook.
In your case, since you do not need to calculate the width in points, just use .ColumnWidth
all along.
n = ColumnNumberOfYourChoice;
width = xlWorksheet.Range.Columns.Item[n].ColumnWidth;
xlWorksheet.Columns[5].ColumnWidth = width;
width_of_first_col = xlWorksheet.Range.Columns.Item[1].ColumnWidth;
xlWorksheet.Columns[6].ColumnWidth = width_of_first_col;
Note from the documentation:
If all columns in the range have the same width, the ColumnWidth property returns the width. If columns in the range have different widths, this property returns Null.
Upvotes: 1
Reputation: 73
Excel manages width of columns in multiple ways.
Upvotes: 2