在实际的项目开发中,报表导出是很常见的功能,下面我用自己的方式讲讲我平时是怎么导出报表的:
① 引入NPOI相关动态库
using NPOI.HSSF.UserModel;
using NPOI.HPSF;
using NPOI.HSSF.Util;
using NPOI.POIFS.FileSystem;
using NPOI.SS.UserModel;
using System.IO;
② 做一些导出的基本设置
IWorkbook workbook = new HSSFWorkbook();
ISheet sheet = workbook.CreateSheet("Sheet1");
//调用列宽自动适应
IRow headerRow = sheet.CreateRow(0);
//设置边框样式
HSSFCellStyle style = (HSSFCellStyle)workbook.CreateCellStyle();
style.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
style.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
style.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
style.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
style.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;
style.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
//设置字体
IFont font = workbook.CreateFont();
font.FontName = "宋体";
font.FontHeightInPoints = 12;
style.SetFont(font);
③ 查询到数据之后,插入数据进表格
headerRow = sheet.CreateRow(rowSum + 1);
headerRow.Height = 18 * 20;
//获取数据源
List<string> lstStrFoot = new List<string>() { "", "", "制表人:",
userName, "总金额:" + Convert.ToString(Math.Round(money, 2)), "制表
时间:", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "", "", "",
"导出时间段", ":", begin_time, "至", end_time, "", "" };
for (int i = 0; i < lstStrFoot.Count; i++)
{ //设置插入的位置以及样式设定
headerRow.CreateCell(i,
CellType.String).SetCellValue(lstStrFoot[i]);
headerRow.GetCell(i).CellStyle = style;
}
④ 做表格数据的自适应处理
//请根据导出的实际需求设定columnNum
for (int columnNum = 0; columnNum <= 17; 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);
}
⑤ 定义你的文件名称,以及存放位置的处理,做完之后就可能生成你的导出信息了
//定义文件名称
var fileName = "销售统计表" + DateTime.Now.ToString("ddHHmm") + ".xls";
//存放的位置
string path = System.Web.HttpContext.Current.Server.MapPath(@"~\Content\");
//路径存在性判断
if (!System.IO.Directory.Exists(path))
{
System.IO.Directory.CreateDirectory(path);
}
var fileurlname = System.Web.HttpContext.Current.Server.MapPath("~/Content/" + fileName);
//加工处理你的导出信息
using (FileStream fss = new FileStream(fileurlname, FileMode.Create))
{
workbook.Write(fss);
ri.flag = true;
ri.info = "/Content/"+fileName;
}
当然你也可以返回出文件流的形式,这样处理的方式更安全,我的所写只做参考,如果小伙伴们感兴趣,可以出一期文件流的生成方式以及前端如何去接收处理,如有错误,麻烦指正!