上篇介绍了使用NPOI导出Excel的功能,但是我们发现还有一些瑕疵
我们看到这里的宽度并没有“撑满”,没有适应表格内的宽度,我们可以来设置宽度,完整代码如下:
public ActionResult Index()
{
//声明工作表
HSSFWorkbook wk = new HSSFWorkbook();
ISheet sheet = wk.CreateSheet("工作汇报1");
//设置表头
IRow cells = sheet.CreateRow(0);
cells.CreateCell(0).SetCellValue("编号");
cells.CreateCell(1).SetCellValue("任务名称");
cells.CreateCell(2).SetCellValue("核心内容");
//添加10行数据
for (int i = 0; i < 10; i++)
{
IRow rowtemp = sheet.CreateRow(i + 1); //循环行
rowtemp.CreateCell(0).SetCellValue(i + 1);
rowtemp.CreateCell(1).SetCellValue("任务名称" + i);
rowtemp.CreateCell(2).SetCellValue("此任务主要是处理..." + i);
}
//设置自适应宽度
for (int columnNum = 0; columnNum <= 10; columnNum++)
{
int columnWidth = sheet.GetColumnWidth(columnNum) / 256;
for (int rowNum = 1; rowNum <= sheet.LastRowNum; rowNum++)
{
IRow 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;
}
}
}
sheet.SetColumnWidth(columnNum, columnWidth * 256);
}
//导出excel,名字可自定义
MemoryStream memoryStream = new MemoryStream();
wk.Write(memoryStream);
memoryStream.Seek(0, SeekOrigin.Begin);
return File(memoryStream, "application/vnd.ms-excel", "工作汇报.xls");
}
执行上边代码,注意“//设置自适应宽度”部分,我们来看看效果: