在.net中 如何直接取得aspx页面的html源代码啊?(为了以后导出用)

在.net中 如何直接取得aspx页面的html源代码啊?(为了以后导出用),第1张

不知道你要用什么方式导出,其实导出的方案很多,不一定非要取得整个aspx页面的html源码

现在在后台获取aspx页面的源代码还是比较麻烦的。

如果你想只获取body里面的内容,可以直接将body里的所有内容都放到一个带服务器标记的div里面

如:毕激

<body>

<div runat="server" id="strContent">

<!--这个里面放你的源码-->

</div>

</body>

后台:

this.EnableViewState = false

StringWriter tw = new StringWriter()

HtmlTextWriter hw = new HtmlTextWriter(tw)

strContent.RenderControl(hw)

string strHtmlBody=tw.ToString()//这里的即时body里面的html源码

上面这种方式比较简单,但是如果要导出整个html里面的内容银皮就会比较麻烦了

必须重写页面的Render方法,在所有控件渲染的时候获取整个页面的源码。

public string strHtml=""

protected override void Render(HtmlTextWriter writer)

{

StringBuilder ee = new StringBuilder()

StringWriter sw = new StringWriter(ee)

HtmlTextWriter hw = new HtmlTextWriter(sw)

base.Render(hw)

strHtml=ee.ToString()//这里的即时body里面的手搏袜html源码

}

读取文件

//创建一个数据链接

string strCon = " Provider = Microsoft.Jet.OLEDB.4.0 Data Source = c:\\sample.xlsExtended Properties=Excel 8.0"

OleDbConnection myConn = new OleDbConnection ( strCon )

string strCom = " SELECT * FROM [Sheet1$] "

myConn.Open ( )

file://唤竖打开数据链接,得到一个数据集

OleDbDataAdapter myCommand = new OleDbDataAdapter ( strCom , myConn )

file://创建一个 DataSet对象

myDataSet = new DataSet ( )

file://得到自斗链备己的DataSet对象

myCommand.Fill ( myDataSet , "[Sheet1$]" )

file://关闭此数据链接

myConn.Close ( )

写文件

DATAGRID输出EXCEL

System.Web.UI.Control ctl=this.DataGrid1

//DataGrid1是你在窗体中拖放的控件

HttpContext.Current.Response.AppendHeader("Content-Disposition","attachmentfilename=Excel.xls")

HttpContext.Current.Response.Charset ="UTF-8"

HttpContext.Current.Response.ContentEncoding =System.Text.Encoding.Default

HttpContext.Current.Response.ContentType ="application/ms-excel"

ctl.Page.EnableViewState =false

System.IO.StringWriter tw = new System.IO.StringWriter()

System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter (tw)

ctl.RenderControl(hw)

HttpContext.Current.Response.Write(tw.ToString())

HttpContext.Current.Response.End()

如果你的空毁DataGrid用了分页,它导出的是当前页的信息,也就是它导出的是DataGrid中显示的信息。而不是你select语句的全部信息。

为方便使用,写成方法如下:

public void DGToExcel(System.Web.UI.Control ctl)

{

HttpContext.Current.Response.AppendHeader("Content-Disposition","attachmentfilename=Excel.xls")

HttpContext.Current.Response.Charset ="UTF-8"

HttpContext.Current.Response.ContentEncoding =System.Text.Encoding.Default

HttpContext.Current.Response.ContentType ="application/ms-excel"

ctl.Page.EnableViewState =false

System.IO.StringWriter tw = new System.IO.StringWriter()

System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter (tw)

ctl.RenderControl(hw)

HttpContext.Current.Response.Write(tw.ToString())

HttpContext.Current.Response.End()

}

用法:DGToExcel(datagrid1)


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/tougao/12116494.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-21
下一篇 2023-05-21

发表评论

登录后才能评论

评论列表(0条)

保存