下面的代码自动调整我的所有列在一个范围内,这工作得很好。问题是,有些列设置为特定宽度,其中所有文本都完美适合,但自动调整会抓取该列并自动调整它,因此会减小列的大小,从而改变图表的总宽度。有没有一种方法可以在自动调整列之前进行检查,以确保我只自动调整由于列大小太小而单元格中的文本不适合的列?
// Get the range that should be auto-fitted.
IRange range = workbook.ActiveWorksheet.Cells[img.cellRange];
// Iterate over your range in column "chunks", e.g., for your example range
// of G6:Q39 it would be split and loop over G6:G39, H6:H39, I6:I39, etc.
foreach (IRange column in range.Columns){
// Only auto-fit if the column is visible.
if (!column.Hidden){
column.AutoFit();
}
}
不存在指示 AutoFit() 仅增加列的选项/在内容较短的情况下避免缩小列的选项;也没有办法检测列何时可能收缩——除非实际调用 AutoFit()。
因此,您可以做的是在调用 AutoFit() 之前保存每列的宽度,然后如果发现新宽度比以前小,则恢复到该宽度。示例:
// Get the range that should be auto-fitted.
IRange range = workbook.ActiveWorksheet.Cells[img.cellRange];
// Iterate over your range in column "chunks", e.g., for your example range
// of G6:Q39 it would be split and loop over G6:G39, H6:H39, I6:I39, etc.
foreach (IRange column in range.Columns)
{
// Only auto-fit if the column is visible.
if (!column.Hidden)
{
// Save off column width prior to auto-fitting.
double colWidthBefore = column.ColumnWidth;
// Call AutoFit which will grow or shrink the column as needed.
column.AutoFit();
// Revert back to the origial width if the column shrank.
if (column.ColumnWidth < colWidthBefore)
column.ColumnWidth = colWidthBefore;
}
}