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

孤街浪徒 提交于 2019-12-10 17:16:14

问题


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 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?


回答1:


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?




回答2:


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


来源:https://stackoverflow.com/questions/2760168/can-i-set-auto-width-on-an-open-xml-sdk-generated-spreadsheet-without-calculatin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!