webservse导出excel和word

         //导出EXCEL
        function game_Excel() {
            var platname =encodeURI( $("#slectplat").val());//加密(是为了防止有中文)
            $("#ExcelForm").attr("action", "AjaxHandle/ExportExcel.ashx?type=game&plat=" + platname + "&time=" + time + "&impormcount=" + count + "&adomParameter=" + Math.floor(Math.random() * 1000 + 1));
          
            document.getElementById("ExcelForm").submit();

        }


<form id="form1"><input id="Button1" onclick="game_Excel()" type="button" value="导出EXCEL" /></form>
<form id="ExcelForm" style="display: none;" action="AjaxHandle/ExportExcel.ashx" method="post"></form>

两个FORM,一个FORM添加一个导出按钮,另一个提交数据

 

ExportExcel.ashx

            context.Response.ContentType = "text/plain";
            string strContent = "";
             string strName = "";//文件名
                string platType = context.Server.UrlDecode((context.Request["plat"] ?? string.Empty).ToString());//游戏平台
                string platTime = context.Request.Params["time"];//时间
                strName=platType + "_" + platTime;
                DateTime dtime = DateTime.ParseExact(platTime, "yyyy-MM", System.Globalization.CultureInfo.CurrentCulture);//选中时间
                string count = context.Request.Params["impormcount"];//时间
                string where_str = string.Format(" and plat='{0}' and [time]='{1}' and importcount={2}", platType, dtime.ToString("yyyyMM"), count);
                Model.GameData gd = new Model.GameData();
                strContent = gd.GameTable(where_str);
            string officeType = "ToExcel";
         
            //string officeType = (context.Request["Type"] ?? string.Empty).ToString();
            //string strReportName = context.Server.UrlDecode((context.Request["Name"] ?? string.Empty).ToString());
            HttpResponse Response = context.Response;
            Response.ClearContent();
            Response.Charset = "UTF-8";
            Response.AddHeader("content-disposition", "attachment; filename=" + HttpUtility.UrlEncode(strName, System.Text.Encoding.UTF8).Replace("+", "%20")
                + (officeType == "ToWord" ? ".doc" : ".xls"));
            Response.ContentType = officeType == "ToWord" ? "application/ms-word" : "application/excel";
            Response.Write("<html><head><title>" + strName + "</title><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"></head><body>");
            //内容
            System.IO.StringWriter sw = new System.IO.StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            hw.Write(strContent);
            Response.Write(sw.ToString());

            Response.Write("</body></html>");
            Response.End();

 

posted on 2012-05-07 14:03  张扬个性,敢为天下先  阅读(1181)  评论(2编辑  收藏  举报