日期:2014-05-18  浏览次数:20446 次

asp.net怎样将当前页面存成excel并提示下载
如题   谢谢

------解决方案--------------------
up
------解决方案--------------------
不懂,学习中,帮你up
------解决方案--------------------
Response.ContentType = "application/vnd.ms-excel "
' Remove the charset from the Content-Type header.从内容类型倒栽跳水取消charset
Response.Charset = " "
' Turn off the view state.关闭看法状态
Me.EnableViewState = False
Response.ContentEncoding = System.Text.Encoding.Default
Dim tw As New System.IO.StringWriter
Dim hw As New System.Web.UI.HtmlTextWriter(tw)

' Get the HTML for the control.得到HTML 为控制
Me.Page.RenderControl(hw)
'me.page 是保存本页面的
' Write the HTML back to the browser.写HTML 回到浏览器
Response.Write(tw.ToString())
' End the response.结束反应
Response.End()
------解决方案--------------------
/// <summary>
/// 导出到excel
/// </summary>
/// <param name= "Filename "> 导出的文件名 </param>
/// <param name= "ctl "> 要导出内容的控件 </param>
/// <param name= "page "> Page </param>
public void ExportToExcel(string Filename, Control ctl, Page page)
{
page.Response.Clear();
// 防止中文内容为乱码
page.Response.ContentEncoding = System.Text.Encoding.GetEncoding( "utf-8 ");
page.Response.Cache.SetCacheability(HttpCacheability.NoCache);
page.Response.ContentType = "application/vnd.xls ";
//可令中文文件名不为乱码
page.Response.AppendHeader( "content-disposition ", "attachment;filename=\ " " + System.Web.HttpUtility.UrlEncode(Filename, System.Text.Encoding.UTF8) + ".xls\ " ");
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
ctl.RenderControl(htw);
page.Response.Write(sw.ToString());
page.Response.End();
}

调用:

ExportToExcel( "文件.xls ",this,this);
------解决方案--------------------
因为 css 文件没有下载下来

下载的时候,可以将 css 内联进 aspx 页面,
------解决方案--------------------
生成的excel文件打开后老是提示无法加载css文件,怎样解决?
-----------------------------------
是因为你把CSS文件也写到excel中。

解决方法:

1、不要把整个页面输出到excel,只输出body部分,但这样就没有CSS效果了

2、你link到页面的CSS的href= "../style.css " 改成绝对路径,比如
href= "http://www.csdn.net/style.css "

因为你使用的是相对路径,excel无法加载
------解决方案--------------------
此法将html中所有的内容,如按钮,表格,图片等全部输出到Execl中。

Response.Clear();
Response.Buffer= true;
Response.AppendHeader( "Content-Disposition ", "attachment;filename= "+DateTime.Now.ToString( "yyyyMMdd ")+ ".xls ");
Response.ContentEncoding=System.Text.Encoding.UTF8;
Response.ContentType = "application/vnd.ms-excel ";
this.EnableViewState = false;

这里我们利用了ContentType属性,它默认的属性为text/html,这时将输出为超文本,即我们常见的网页格式到客户端,如果改为ms-excel将将输出excel格式,也就是说以电子表格的格式输出到客户端,这时浏览器将提示你下载保存。ContentType的属性还包括:image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword 。同理,我们也可以输出(导出)图片、word文档等。下面的方法,也均用了这个属性。