How to get and set excel column width through c# e

2019-09-14 00:56发布

问题:

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.

回答1:

Excel manages width of columns in multiple ways.

  • The Columnwidth property returns or sets the width of columns as the number of characters of the normal font that can be accommodated in one column. Please refer to this link.
  • The width property gives the width in points of a range as specified here.