开发者

Can I set auto-width on an Open XML SDK-generated spreadsheet without calculating the individual widths?

开发者 https://www.devze.com 2022-12-29 04:32 出处:网络
I\'m working on creating an Excel file from a large set of data by using the Open XML SDK. I\'ve finally managed to get a functional Columns node, which specifies all of the columns which will actuall

I'm working on creating an Excel file from a large set of data by using the Open XML SDK. I've finally managed to get a functional Columns node, which specifies all of the columns which will actually be used in the file. There is a "BestFit" property that can be set to true, but this apparently does not do anything. Is there a way to automatically 开发者_JAVA技巧set these columns to "best fit", so that when someone opens this file, they're already sized to the correct amount? Or am I forced to calculate how wide each column should be in advance, and set this in the code?


The way I understand the spec and this MSDN discussion, BestFit tells you the width was auto-calculated in Excel, but it does not tell Excel that it should calculate it again next time it is opened.

As "goodol" indicates in that discussion, I think the width can only be calculated when you display the column, since it depends on the contents, the font used, other style parameters... So even if you want to pre-calculate the width yourself, be aware that this is only an estimation, and it can be wrong if the contents contain lots of "wide" characters. Or does the Open XML SDK do this for you?


I'm using EPPlus which I highly recommend. Took me a while to figure out how to do it using that, here's what I came up with:

// Get your worksheet in "sheet" variable

// Set columns to auto-fit
for (int i = 1; i <= sheet.Dimension.Columns; i++)
{
    sheet.Column(i).AutoFit();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消