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();
}
精彩评论