Search code examples
c#excelspreadsheetgear

Autofit columns in excel only when text is getting cut off


The code below autofits all my columns within a range, this is working perfectly fine. The issue is that there are some columns that are set to a specific width, where all the text fits perfectly fine, but autofit grabs that columns and autofits it therefore decreasing the size of the column hence changing the total width of the chart. Is there a way I can check before autofitting the column to make sure I'm only autofitting columns where the text in the cell doesn't fit due to the column size being too small?

// 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();
                    }
                }

Sample of what the chart should look like: enter image description here

vs what it looks like after autofit: enter image description here


Solution

  • No option exists to instruct AutoFit() to only increase a column's with / refrain from shrinking it in the case of shorter content; nor is there a way to detect when a column might shrink--not without actually calling AutoFit().

    So, what you could do is save off each column's width prior to calling AutoFit() and then revert back to that width if you find the new width is smaller than before. Example:

    // 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;
        }
    }