NPOI自带的列宽自适应方法只支持英文和数字,若要支持中文需要自己添加方法
//列宽自适应,只对英文和数字有效
for (int i = 0; i <= MaxColumn; i++)
{
sheet.AutoSizeColumn(i);
}
//列宽自适应,支持中文
for (int columnNum = 0; columnNum <= MaxColumn; columnNum++)
{
int columnWidth = sheet.GetColumnWidth(columnNum) / 256;
for (int rowNum = 1; rowNum <= sheet.LastRowNum; rowNum++)
{
IRow currentRow;
//当前行未被使用过
if (sheet.GetRow(rowNum) == null)
{
currentRow = sheet.CreateRow(rowNum);
}
else
{
currentRow = sheet.GetRow(rowNum);
}
if (currentRow.GetCell(columnNum) != null)
{
ICell currentCell = currentRow.GetCell(columnNum);
int length = Encoding.Default.GetBytes(currentCell.ToString()).Length;
if (columnWidth < length)
{
columnWidth = length+3; //+3是为了美观
}
}
}
sheet.SetColumnWidth(columnNum, columnWidth * 256);
}