How can columns be set to 'autosize' in Excel documents created with NPOI?

南笙酒味 提交于 2019-11-27 15:54:06

问题


NPOI is a .NET port of the Java POI project, which allows one to read and write Microsoft Excel documents (as well as other Office formats). NPOI 1.2.2 has introduced support for 'autosizing' columns, whereby the column is set to the width of the widest cell entry in the column. However, there are many reports that this does not work. So is it possible?


回答1:


I've posted this just to answer it, so as to provide a record. It is possible to make columns autosized using NPOI, but you have to add all the data in columns, rather than in rows. Once all the cells have been added to a column @ columnIndex you then call

mySheet.AutoSizeColumn(columnIndex)

and move to the next column. I have found no other way to make this functionality work.




回答2:


As already indicated by Yellowfog the following will work

mySheet.AutoSizeColumn(columnIndex)

However some abiguity appears in the posts. It seems to be a method that only works after you have completed entering data, styles etc. So that this will work

ISheet mySheet = hssfworkbook.CreateSheet("sheet1");
IRow row = mySheet.CreateRow(0);
ICell cell = row.CreateCell(0);
cell.SetCellValue("foo");
mySheet.AutoSizeColumn(0);

but the following will have no effect (because it has no information to auto size against)

ISheet mySheet = hssfworkbook.CreateSheet("sheet1");
mySheet.AutoSizeColumn(0);
IRow row = mySheet.CreateRow(0);
ICell cell = row.CreateCell(0);
cell.SetCellValue("foo");


来源:https://stackoverflow.com/questions/3151806/how-can-columns-be-set-to-autosize-in-excel-documents-created-with-npoi

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