B. Clay Shannon B. Clay Shannon - 1 month ago 8
C# Question

Why does attempting to autofit the width of a sheet, or a single column on that sheet, fail?

I have one column whose contents are truncated, and I'd like to avoid having to 2-click the right column gutter to see the data. First I tried autofitting the entire shebang:

private void PopulatePivotTableDataSheet()
{
if (null == _produceUsagePivotDataList) return;
AddColumnHeadingRowPivotData();
foreach (ProduceUsagePivotData pupd in _produceUsagePivotDataList)
{
AddPivotData(pupd.ItemCode, pupd.ItemDescription, pupd.Unit, pupd.MonthYear, pupd.Quantity,
pupd.TotalPrice, pupd.IsContractItem);
}
_xlPivotDataSheet.Cells.AutoFit();
}


...but the last line fails with "AutoFit method of Range class failed"

Then I tried applying it to just the column in question like so:

private void AddPivotData(String ItemCode, String ItemDescription, String Unit, String MonthYear, int Quantity, Decimal TotalPrice, Boolean IsContractItem)
{
var itemCodeCell = _xlPivotDataSheet.Cells[_lastRowAddedPivotTableData + 1, 1];
itemCodeCell.Value2 = ItemCode;

var itemDescriptionCell = _xlPivotDataSheet.Cells[_lastRowAddedPivotTableData + 1, 2];
itemDescriptionCell.Value2 = ItemDescription;
itemDescriptionCell.AutoFitWidth();
. . .


...and that last line fails with, "'System.__ComObject' does not contain a definition for 'AutoFitWidth'"

What in Sam Hill o' beans is going on here? Autofitting should be easily doable, shouldn't it?

Answer

This will apply AutoFit to the columns comprising the range:

_xlPivotDataSheet.Cells.EntireColumn.AutoFit();