效果图:
前端页面
<html> <head> <title>Test For Excel</title> <script src="js/jquery.js" /> <script type="text/javascript"> function btnDownExel_Click() {var url = "TScheduleRExcelDown.aspx"; window.open(url); } </script> </head> <body> <div class="form-group" style="margin-left:15%"> <input type="button" name="btnSearch" id="btnDownExel" class="btn btn-default" onclick="btnDownExel_Click()" value="DownExcel" /> </div> </body> </html>
后台页面:TScheduleRExcelDown.aspx.cs
protected void Page_Load(object sender, EventArgs e) { string sqlNode= "/*你的SQL语句*/"; //返回table DataTable dtAll = DBFunction.ExecuteTableSql(sqlNode); DownExcel(dtAll); } /// <summary> /// 下载Excel档 /// </summary> /// <param name="dt">数据源</param> public void DownExcel(DataTable dt) { HttpResponse resp = System.Web.HttpContext.Current.Response; resp.Charset = "utf-8"; resp.Clear(); string filename = "在装修店铺表_" + DateTime.Now.ToString("yyyyMMdd"); resp.AppendHeader("Content-Disposition", "attachment;filename=" + filename + ".xls"); resp.ContentEncoding = System.Text.Encoding.UTF8; resp.ContentType = "application/ms-excel"; string style = "<meta http-equiv="content-type" content="application/ms-excel; charset=utf-8"/>" + "<style> .table{ font: 9pt Tahoma, Verdana; font-weight:bold; color: #000000; text-align:center; background-color:#8ECBE8; }.tableTd{text-align:center;height:21px;background-color:#EFF6FF;}.tdNode{text-align:left;height:21px;background-color:#DDDDFF;}.table th{ font: 9pt Tahoma, Verdana; color: #000000; font-weight: bold; background-color: #8ECBEA; height:25px; text-align:center; padding-left:10px;}</style>"; resp.Write(style); resp.Write("<table class='table'><tr><th>商场</th><th>铺位编号</th><th>装修联系人</th><th>装修联系电话</th><th>装修日期</th></tr>"); foreach (DataRow tmpRow in dt.Rows) { resp.Write("<tr><td class='tableTd'>" + tmpRow["BMarketName"].ToString() + "</td><td class='tableTd'> " + tmpRow["BStoreCode"].ToString() + "_" + tmpRow["BStoreName"].ToString() + " </td><td class='tableTd'>" + tmpRow["BContactor"].ToString() + "</td><td class='tableTd'>" + tmpRow["BContactPhone"].ToString() + "</td><td class='tableTd'>" + tmpRow["BCreatedTime"].ToString() + "</td></tr>"); } resp.Write("<table>"); resp.Flush(); resp.End(); }