AaronLS
AaronLS

Reputation: 38394

Get list of column widths within a range?

Using EPPlus, is there a way to determine the widths of columns within a range?

Let's say I want to get the widths of columns 1 through 10 after performing an AutoFit:

// autofit columns 1 through 10 based on all data
worksheet.Cells[2, 1, numberOfRows + 2, 10].AutoFitColumns(22, 50);
// determine resulting widths
List<double> columnWidths = worksheet.Cells[2, 1, 2, 10]
    .Select(s=> s.Width/* doesn't work, no Width property */ ).ToList();

This does not work, because .Cells generates an IEnumerable<ExcelRangeBase> and each item in ExcelRangeBase is itself a nested ExcelRangeBase, which seems to go on forever. So no amount of .Select ever reaches a list of cells. The Cells index is crafted to only generate a single row of cells, for which I hoped to get the Width for each one. Not sure if there is an elegant way to accomplish this.

How do I populate columnWidths with a list of the widths of columns 1 through 10?

Upvotes: 1

Views: 1114

Answers (2)

Stewart_R
Stewart_R

Reputation: 14515

Well, you can reach an ExcelCellAddress object for the first cell in a range from from the .Start property of an ExcelRangeBase object.

Which leads to this alternative approach:

List<double> columnWidths = worksheet.Cells[2, 1, 2, 10]
    .Select(s => worksheet.Column(s.Start.Column).Width)
    .ToList(); 

I think its slightly better but elegance is firmly in the eye of the beholder! :-)

Upvotes: 3

AaronLS
AaronLS

Reputation: 38394

This is what I came up with for now, but welcome any answers that propose something more elegant:

List<double> dataWidths = new List<double>(10);
for(int i= 0; i < 10; ++i)
{
    dataWidths.Add( worksheet.Column(i + 1).Width );
}

Upvotes: 0

Related Questions