在服务器端,将sqlserver中的数据生成了excel文件,现在只能在服务器端打开,我想下载到客户端,该如何实现,从网上查了一段代码,也可以在客户端提示保存文件,可是excel中却没有数据代码: string path = HttpContext.Current.Server.MapPath("huizong1.xls");
System.IO.FileInfo file = new System.IO.FileInfo(path);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Charset = "GB2312";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpContext.Current.Server.UrlEncode(file.Name));
HttpContext.Current.Response.AddHeader("Content-Length", file.Length.ToString());
HttpContext.Current.Response.ContentType = "application/ms-excel";
HttpContext.Current.Response.WriteFile(file.FullName); HttpContext.Current.Response.End(); 谢谢!
System.IO.FileInfo file = new System.IO.FileInfo(path);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Charset = "GB2312";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpContext.Current.Server.UrlEncode(file.Name));
HttpContext.Current.Response.AddHeader("Content-Length", file.Length.ToString());
HttpContext.Current.Response.ContentType = "application/ms-excel";
HttpContext.Current.Response.WriteFile(file.FullName); HttpContext.Current.Response.End(); 谢谢!
response.writefile("cache.xls")
protected void Page_Load(object sender, EventArgs e)
{
//将数据先装入到DataTable dt中
string reporttype = "excel";
GridView dtView = new GridView();
dtView.DataSource = dt.DefaultView;
dtView.DataBind();
CreateReport(dtView, reporttype, "ss.xls");
//CreateReport(dtView, "word", "ss.doc");
}
/// <summary>
/// 创建报表文档
/// </summary>
/// <param name="dtView">存数据的GridView</param>
/// <param name="reporttype">报表类型</param>
/// <param name="FileName">文档名称</param>
public void CreateReport(GridView dtView, string reporttype, string FileName)
{ Response.Clear();
Response.Buffer = false;
Response.Charset = "GB2312";
Response.ContentEncoding = System.Text.Encoding.Default;
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
Response.AppendHeader("Content-Disposition", "attachment;filename=" + FileName);
if (string.CompareOrdinal("excle", reporttype))
{
Response.ContentType = "application/vnd.ms-excel";
}
else if (string.CompareOrdinal("word", reporttype))
{
Response.ContentType = "application/vnd.ms-word";
}
this.EnableViewState = false;
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
dtView.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.End(); } 不用在服务器端生成,直接调这个页面就,打开就OK了