一开始以为centos没有中文字体报错,在尝试了添加字体以后,仍然报这个错。
问题出在下面这段代码自适应列宽上:
for (int j = 0; j <= 14; j++)
{
sheet.AutoSizeColumn(j);//自适应列宽
}
网上搜索到说这个自适应列宽只适用于英文和数字,不适用中文 。
更改使用网上大佬如下代码自适应列宽后解决报错问题:
for (int columnNum = 0; columnNum <= 14; 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);
}