MVC +NPOI+AJAX 查询并生成excel 下载
Controller 代码:
public class SubArea2STIReportController : BaseController { [ActionDescription("分区2STI查询")] public ActionResult Index() { var vm = CreateVM<SubArea2STIReportVM>(); return PartialView(vm); } [HttpPost] [ActionDescription("分区2STI查询")] public ActionResult Index(string NetworkStandard, string BusinessModel, string Model, string FinialYearStart, string FinialYearEnd) { if (string.IsNullOrEmpty(FinialYearStart)) { var script = "Ext.Msg.alert(‘提示‘, ‘请填写开始时间‘);"; return Content(script); } if (string.IsNullOrEmpty(FinialYearEnd)) { var script = "Ext.Msg.alert(‘提示‘, ‘请填结束时间‘);"; return Content(script); } else { string YearStartNumber = FinialYearStart.Substring(0, 4); string YearStart = YearStartNumber + @"-01-01"; string YearEndNumber = FinialYearEnd.Substring(0, 4); string YearEnd = YearEndNumber + @"-01-01"; int span = int.Parse(YearEndNumber) - int.Parse(YearStartNumber); if (span > 3) { var script = "Ext.Msg.alert(‘提示‘, ‘系统最多可查询三年数据‘);"; return Content(script); } //查询条件 SqlParameter[] parms = { new SqlParameter("@NetworkStandard",NetworkStandard), new SqlParameter("@BusinessModel",BusinessModel), new SqlParameter("@Model",Model), new SqlParameter("@StartDate",YearStart), new SqlParameter("@EndDate",YearEnd) }; //调用存储过程查询返回DataSet DataSet result = DC.Database.RunSP("Pro_UploadData_SubArea2STI", parms); if (result == null || result.Tables.Count < 1) { var script = "Ext.Msg.alert(‘提示‘, ‘查询结果为空‘);"; return Content(script); } else { //创建个excel NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook(); NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet("分区2"); int columns = result.Tables[0].Columns.Count; //添加第一行 #region string fy = "FY"; fy += FinialYearStart.Substring(2, 2); fy += "累计"; NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow(0); row1.CreateCell(0).SetCellValue("分区"); row1.CreateCell(1).SetCellValue("省份"); row1.CreateCell(2).SetCellValue("STI累计"); row1.CreateCell(3).SetCellValue(fy); for (int i = 0; i < columns - 4; i++) { //获取DataSet标题行,动态生成excel的标题 string title = result.Tables[0].Columns[i+4].ColumnName.ToString() ; string year = title.Substring(2, 2); string month = String.Empty; if (title.Length == 6) { month = title.Substring(5, 1); } else { month = title.Substring(5, 2); } switch (month) { case "1": month = "Jan-"; break; case "2": month = "Feb-"; break; case "3": month = "Mar-"; break; case "4": month = "Apr-"; break; case "5": month = "May-"; break; case "6": month = "Jun-"; break; case "7": month = "Jul-"; break; case "8": month = "Aug-"; break; case "9": month = "Sep-"; break; case "10": month = "Oct-"; break; case "11": month = "Nov-"; break; case "12": month = "Dec-"; break; } title = month + year; row1.CreateCell(i + 4).SetCellValue(title); } #endregion //第二行开始添加数据 for (int r = 0; r < result.Tables[0].Rows.Count; r++) { NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(r+1); for (int c = 0; c < columns; c++) { rowtemp.CreateCell(c).SetCellValue(string.IsNullOrEmpty(result.Tables[0].Rows[r][c].ToString()) ? "" : result.Tables[0].Rows[r][c].ToString()); } } System.IO.MemoryStream ms = new System.IO.MemoryStream(); book.Write(ms); string fileguid = Guid.NewGuid().ToString(); //获取临时文件目录 string TempExportDir = ConfigurationSettings.AppSettings["TempExportDir"].ToString(); string Filepath = @TempExportDir + "\\" + fileguid + ".xls"; //在临时文件目录生成excel System.IO.File.WriteAllBytes(Filepath, ms.ToArray()); string html = "<table class=‘form‘><tr><td>文件已准备完毕,请点击下方链接下载</td></tr>"; html += "<tr><td><a href=‘#‘ onclick=\\\"LL_DownloadExportedFile(‘" + fileguid + "‘);return false;\\\">查询结果.xls</a></td></tr></table>"; var script2 = string.Format("var html = \"{3}\";FF_OpenPostDialog(\"{0}\", {1}, {2}, html, \"{4}\", {5});", "查询结果", 250, 100, html, "ExportExcel", 1); return Content(script2); } } }
View代码:
@model MBGCPB3S.ViewModels.ReportData.SubArea2STIReportVMs.SubArea2STIReportVM @using (Extjs.BeginForm(width: 400, flex: 1,id:"Excelform",labelWidth:160)) { using (Extjs.BeginItems()) { using (Extjs.BeginFieldContainer(layout: ExtLayoutEnum.hbox)) { Extjs.LabelAndComboBoxFor(x => x.FinialYearStart, x => x.FinialYear); Extjs.LabelAndComboBoxFor(x => x.FinialYearEnd, x => x.FinialYear); } using (Extjs.BeginFieldContainer(layout: ExtLayoutEnum.hbox)) { Extjs.LabelAndComboBoxFor(x => x.NetworkStandard, x => x.NetworkStandards); Extjs.LabelAndComboBoxFor(x => x.BusinessModel, x => x.BusinessModels); } using (Extjs.BeginFieldContainer(layout: ExtLayoutEnum.hbox)) { Extjs.LabelAndTextFor(x => x.Model); } using (Extjs.BeginFieldContainer(layout: ExtLayoutEnum.vbox, valign: ExtVBoxAlignEnum.center)) { Extjs.Button(id: "postexcel", onClick: "events()",buttonText:"生成"); } } } <script type="text/javascript"> function events() { $(document).ready(function () { var NetworkStandard = $("input[name = ‘NetworkStandard‘]").val(); var BusinessModel = $("input[name = ‘BusinessModel‘]").val(); var Model = $("input[name = ‘Model‘]").val(); var FinialYearStart = $("input[name = ‘FinialYearStart‘]").val(); var FinialYearEnd = $("input[name = ‘FinialYearEnd‘]").val(); $.post(‘@BaseController.VirtualDir‘ + ‘/SubArea2STIReport/Index?NetworkStandard=‘ + NetworkStandard + ‘&BusinessModel=‘ + BusinessModel + ‘&Model=‘ + Model + ‘&FinialYearStart=‘ + FinialYearStart + ‘&FinialYearEnd=‘ + FinialYearEnd + ‘‘, function (s) { eval(s);}); //生成一个对话框 function FF_OpenPostDialog(Title, Width, Height, Html, DialogID, NoPost) { if (DONOTUSE_isCtrl == true) { DONOTUSE_isCtrl = false; var win = window.open("/Home/PopUpIndex", "_blank"); if (win.addEventListener) { win.addEventListener(‘load‘, function () { $("body", win.document).append(Html); }, false); } else if (win.attachEvent) { win.attachEvent(‘onload‘, function () { $("body", win.document).append("<div id=‘DONOTUSE_POSTFORM‘>" + Html + "</div>"); }); } } else { var id = DialogID != undefined ? Ext.id() : DialogID; var id2 = id + "div"; var win = new Ext.Window({ id: id, layout: ‘fit‘, title: Title, width: Width, html: "<div id=‘" + id2 + "‘>" + Html + "</div>", height: Height, modal: true, maximizable: true, autoScroll: false }); if (NoPost == undefined) { win.on("afterrender", function (self, eOpts) { var form = $(self.el.dom).find("form:first"); $.post(form.attr("action"), form.serialize(), function (data) { $(self.el.dom).find("#" + id2).html(data); win.setHeight(null); win.setWidth(null); win.center(); CloseMask(); }); }); ShowMask(); win.showAt(-2000, -2000); } else { win.show(); } } } }); }; //生成个隐藏的form点击时,跳转到controller function LL_DownloadExportedFile(Filepath) { var newForm = $(‘<form>‘); newForm.attr("action", FormatUrl(‘/SubArea2STIReport/DownloadExportedFile‘)); newForm.attr("method", "post"); newForm.attr("target", "hiddenpostif"); var html = "<input type=\"hidden\" id=\"Filepath\" name = \"Filepath\" value=\"" + Filepath + "\" />"; newForm.html(html); $("body").append(newForm); newForm.submit(); newForm.remove(); }; </script>
下载excel controller
[HttpPost] [ActionDescription("下载文件")] public ActionResult DownloadExportedFile(string Filepath) { byte[] exceldata = System.IO.File.ReadAllBytes(@TempExportDir + "\\" + Filepath + ".xls"); return File(exceldata, "application/x-excel", Filepath +".xls"); }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。