文章目录
- 前言
- 一、NPOI优势
- 二、运行逻辑
- 三、安装NOPI组件
- 四、导出Excel---实现代码
- 五、最终效果
- 六、总结
前言
NPOI,就是POI的.NET版本。POI是一套用Java写成的库,能够帮助开发者在没有安装微软Office的情况下读写Office 97-2003的文件,支持的文件格式包括xls, doc, ppt等。
一、NPOI优势
- 完全基于.NET 2.0,而非.NET 3.0/3.5
- 读写速度快
- 稳定性好
- API简单易用,完全支持Excel格式
二、运行逻辑
三、安装NOPI组件
NOPI组件安装非常简单,自行百度
四、导出Excel—实现代码
//获取数据private string fGenerateReport(HttpContext context){string fileurl = "";try{Hashtable jsonranklists = new Hashtable();
#region 声明变量,接收JS中AJAX传输的数据string num = ""; //定位年月日string code = ""; //设备编号string txtdateStart = ""; //开始时间string txtdateEnd = ""; //结束时间if (!string.IsNullOrWhiteSpace(context.Request["num"])){num = context.Request["num"];}if (!string.IsNullOrWhiteSpace(context.Request["code"])){code = context.Request["code"];}if (!string.IsNullOrWhiteSpace(context.Request["num"]) && num == "1"){if (!string.IsNullOrWhiteSpace(context.Request["txtdateStart"])){txtdateStart = context.Request["txtdateStart"];}if (!string.IsNullOrWhiteSpace(context.Request["txtdateEnd"])){txtdateEnd = context.Request["txtdateEnd"];}}if (!string.IsNullOrWhiteSpace(context.Request["num"]) && num == "2"){if (!string.IsNullOrWhiteSpace(context.Request["txtdateStart"])){txtdateStart = context.Request["txtdateStart"];}if (!string.IsNullOrWhiteSpace(context.Request["txtdateEnd"])){txtdateEnd = context.Request["txtdateEnd"];}}if (!string.IsNullOrWhiteSpace(context.Request["num"]) && num == "3"){if (!string.IsNullOrWhiteSpace(context.Request["txtdateStart"])){txtdateStart = context.Request["txtdateStart"];}if (!string.IsNullOrWhiteSpace(context.Request["txtdateEnd"])){txtdateEnd = context.Request["txtdateEnd"];}}
#endregion//将数据传入BLL层查询所需数据放在List<String>中List<tb_ammeterdata> lS = bllreport.ERListexport(num, code, txtdateStart, txtdateEnd);string sExportFileName = ""; //导出的临时文件的名称string sExportFilePath = ""; //导出的临时文件路径try{HSSFWorkbook wb = BuildSwitchData(lS);//string sExportDir = HttpContext.Current.Server.MapPath("~") + "orderdocument"; //临时保存文件夹//根据不同条件生成Excel文件名称string sExportDir = Com.Common.Config.ConfigManage.fGetAppConfig("UploadUrl") + "report";if (num == "2"){sExportFileName = DateTime.Now.ToString("yyyyMMddHHmmss") + "月报表" + ".xls";}else if (num == "3"){sExportFileName = DateTime.Now.ToString("yyyyMMddHHmmss") + "年报表" + ".xls";}else{sExportFileName = DateTime.Now.ToString("yyyyMMddHHmmss") + "日报表" + ".xls";}//拼接Excel的地址sExportFilePath = sExportDir + "/" + sExportFileName;if (!Directory.Exists(sExportDir))Directory.CreateDirectory(sExportDir);using (FileStream file = new FileStream(sExportFilePath, FileMode.Create)){wb.Write(file);}}catch{HttpContext.Current.Response.Write("<script type='text/javascript'>alert('导出发生异常!');window.history.back();</script>");if (File.Exists(sExportFilePath))File.Delete(sExportFilePath);return "";}fileurl = Com.Common.Config.ConfigManage.fGetAppConfig("FileUrl")+ "report" +"/"+ sExportFileName;//HttpContext.Current.Response.ContentType = "application/vnd.ms-excel; charset=UTF-8";//HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + sExportFileName);//HttpContext.Current.Response.TransmitFile(sExportFilePath); //将指定的文件直接写入 HTTP 响应输出流,而不在内存中缓冲该文件//HttpContext.Current.Response.Flush();//if (File.Exists(sExportFilePath))//HttpContext.Current.Response.End();}catch (Exception ex){Com.Common.Utility.Log.WriteLogs("S:" + ex.Message);return "";}return fileurl;}//设置Excel样式private HSSFWorkbook BuildSwitchData(List<tb_ammeterdata> lS){try{HSSFWorkbook wb = new HSSFWorkbook();HSSFSheet sheet = (HSSFSheet)wb.CreateSheet("电量统计报表"); //创建工作表(表格页面名称)sheet.CreateFreezePane(0, 1); //冻结列头行HSSFRow row_Title = (HSSFRow)sheet.CreateRow(0); //创建列头行row_Title.HeightInPoints = 19.5F; //设置列头行高#region 设置列宽sheet.SetColumnWidth(0, 50 * 256);sheet.SetColumnWidth(1, 24 * 256);sheet.SetColumnWidth(2, 37 * 256);sheet.SetColumnWidth(3, 22 * 256);sheet.SetColumnWidth(4, 20 * 256);sheet.SetColumnWidth(5, 20 * 256);#endregion#region 设置列头单元格样式HSSFCellStyle cs_Title = (HSSFCellStyle)wb.CreateCellStyle(); //创建列头样式cs_Title.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center; //水平居中cs_Title.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center; //垂直居中HSSFFont cs_Title_Font = (HSSFFont)wb.CreateFont(); //创建字体cs_Title_Font.Boldweight = 700; //字体加粗cs_Title_Font.FontHeightInPoints = 12; //字体大小cs_Title.SetFont(cs_Title_Font); //将字体绑定到样式#endregion#region 生成列头for (int i = 0; i < 3; i++){HSSFCell cell_Title = (HSSFCell)row_Title.CreateCell(i); //创建单元格cell_Title.CellStyle = cs_Title; //将样式绑定到单元格switch (i){case 0:cell_Title.SetCellValue("序号");break;case 1:cell_Title.SetCellValue("抄表时间");break;case 2:cell_Title.SetCellValue("正向总有工电量(kW.h)");break;}}#endregionfor (int i = 0; i < lS.Count; i++){#region 设置内容单元格样式HSSFCellStyle cs_Content = (HSSFCellStyle)wb.CreateCellStyle(); //创建列头样式cs_Content.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center; //水平居中cs_Content.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center; //垂直居中#endregion#region 生成内容单元格HSSFRow row_Content = (HSSFRow)sheet.CreateRow(i + 1); //创建行row_Content.HeightInPoints = 16;for (int j = 0; j < 3; j++){HSSFCell cell_Conent = (HSSFCell)row_Content.CreateCell(j); //创建单元格cell_Conent.CellStyle = cs_Content;switch (j){case 0:cell_Conent.SetCellValue(i);break;case 1:cell_Conent.SetCellValue(lS[i].creationtime);//这里是将creationtime定义成DateTime类型HSSFCellStyle hSSFCellStyle1 = (HSSFCellStyle)wb.CreateCellStyle();HSSFDataFormat format = (HSSFDataFormat)wb.CreateDataFormat();hSSFCellStyle1.DataFormat = format.GetFormat("yyyy/MM/dd hh:mm");cell_Conent.CellStyle = hSSFCellStyle1;break;case 2:cell_Conent.SetCellValue(lS[i].epplus);break;}}#endregion}return wb;}catch { return null; }}
五、最终效果
六、总结
本文主要讲了NPOI实现对数据库数据导出功能,NPOI目前有好几个assembly,每个的作用各有不同,开发人员可以按需加载相应的assembly。在这里大概罗列一下:
NPOI.Util 基础辅助库
NPOI.POIFS OLE2格式读写库
NPOI.DDF Microsoft Drawing格式读写库
NPOI.SS Excel公式计算库
NPOI.HPSF OLE2的Summary Information和Document Summary Information属性读写库
NPOI.HSSF Excel BIFF格式读写库