//前端页面 <body> <input type="button" value="导出Excel" class="button" id="btnjbntExport" runat="server" onclick="Exportjbnt()"/> <table class="table"> <thead> <th colspan="3">基本农田保护区面积统计表(公顷)</th> </thead> <tbody> <tr> <td>基本农田占用总面积</td> <td id="JBNTZMJ">0.00</td> </tr> </tbody> </table> <form id="jbntform" action="./GisUtility/GeometryHelper.ashx" method="post"> //用js操作文件流,所以用form的post方法是一个不错的选择 <input type="hidden" id="jbntarea" name="jbntarea" />//传递参数到后台 <input type="hidden" id="jbnttype" name="jbnttype" /> </form> </body>
//加载前端面前先加载包涵下面方法的js文件
function Exportjbnt() { var area = GetJbntValue(); $("#jbnttype").val("exportjbnt"); $("#jbntarea").val(area); $("#jbntform").submit(); } function GetJbntValue() { var areavalue = $("#JBNTZMJ").html(); return areavalue; }
//GeometryHelper.ashx中的后台方法
if (context.Request.Form["jbnttype"] == "exportjbnt")//导出基本农田表格到excel { string area = context.Request.Params["jbntarea"]; string tile = "基本农田保护区面积统计表(公顷)"; pGeoJson= CommUtility.ExportJbnt2Excel(tile,area); }
//创建excel
public static string ExportJbnt2Excel(string Exceltitle, string area) { //创建工作薄 HSSFWorkbook wk = new HSSFWorkbook(); //创建一个名称为Sheet1的表 ISheet tb = wk.CreateSheet(); wk.SetSheetName(0,"Sheet1"); for (int i = 0; i < 2; i++) { ICellStyle cellStyle = SetCellStyle(wk, i); IRow row = tb.CreateRow(i); for (int j = 0; j < 6; j++) { ICell cell = row.CreateCell(j); cell.CellStyle = cellStyle; } } MergeCell(tb, tb.GetRow(0).GetCell(2), 0, 0, 2, 5, Exceltitle); MergeCell(tb, tb.GetRow(1).GetCell(0), 1, 1, 0, 3, "基本农田占用总面积"); MergeCell(tb,tb.GetRow(1).GetCell(4),1,1,4,5,area); MemoryStream mstream = new MemoryStream(); wk.Write(mstream); DownloadFile(mstream, Exceltitle); return null; }
//在客户端保存或查看用流生成的excel文件 public static string DownloadFile(MemoryStream fs, string filename)//必须为FileStream或MemoryStream ,如果用Stream则生成的excel无法正常打开{
string fileName = filename+".xls";//客户端保存的文件名 //以字符流的形式下载文件
byte[] bytes = fs.ToArray(); fs.Read(bytes, 0, bytes.Length); fs.Close();
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.ClearContent();
System.Web.HttpContext.Current.Response.ClearHeaders();
System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream";
//通知浏览器下载文件而不是打开
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
System.Web.HttpContext.Current.Response.AddHeader("Content-Transfer-Encoding", "binary"); System.Web.HttpContext.Current.Response.BinaryWrite(bytes);
System.Web.HttpContext.Current.Response.Flush();
System.Web.HttpContext.Current.Response.End();
return null; }