如何通过c#excel interop获取和设置excel列宽

时间:2015-09-04 07:33:26

标签: c# excel excel-interop

我在创建excel时使用excel互操作。现在,我必须得到一个列的大小作为下一列的大小的基础。我尝试了以下代码:

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;

结果应该是第4列和第5列具有相同的大小,以及第1列和第6列。但是这不符合确切的结果。

将单元格的设置设置为另一个单元格的最佳方法是什么。感谢。

2 个答案:

答案 0 :(得分:1)

Excel以多种方式管理列的宽度。

  • Columnwidth 属性返回或设置列的宽度,作为一列中可容纳的普通字体的字符数。请参阅此link
  • 宽度属性提供指定范围here范围内的宽度。

答案 1 :(得分:0)

Range.Width是只读属性,可为您提供以磅为单位的宽度。

Range.ColumnWidth是一个读/写属性,它为您提供了我喜欢的字符单位宽度。字符单位表示由工作簿的0样式定义的字体类型和大小下的字符Normal的宽度。

在这种情况下,由于您无需计算点的宽度,因此始终使用.ColumnWidth

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;

documentation的注释:

如果范围中的所有列都具有相同的宽度,则ColumnWidth属性将返回宽度。如果范围内的列具有不同的宽度,则此属性返回Null。

相关问题