NPOI自帶的列寬自適應(yīng)方法只支持英文和數(shù)字,若要支持中文需要自己添加方法
//列寬自適應(yīng),只對(duì)英文和數(shù)字有效
for (int i = 0; i <= MaxColumn; i++)
{
sheet.AutoSizeColumn(i);
}
//列寬自適應(yīng),支持中文
for (int columnNum = 0; columnNum <= MaxColumn; columnNum++)
{
int columnWidth = sheet.GetColumnWidth(columnNum) / 256;
for (int rowNum = 1; rowNum <= sheet.LastRowNum; rowNum++)
{
IRow currentRow;
//當(dāng)前行未被使用過
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);
}