导出DataGrid中的数据到Excel,Word,Text

本文介绍了一种方法,可以将ASP.NET中的DataGrid数据导出到Excel、Word文件和TXT文本文件中。通过使用HttpServletResponse对象设置响应头并指定文件类型,再利用StringWriter和HtmlTextWriter来渲染DataGrid控件,最后输出到相应的文件格式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 【转自】 http://hi.baidu.com/mr%5Findigo/blog/item/7ad19aa5dfbab4ff9152ee5b.html

 

Exporting DataGrid to Excel
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
myDataGrid.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
Exporting the DataGrid to a Word file
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=FileName.doc");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.word";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
myDataGrid.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
Exporting a DataGrid to a Text File
//组织数据源
System.Data.DataTable dt = new System.Data.DataTable();
dt.Columns.Add("学号");
dt.Columns.Add("姓名");
dt.Columns.Add("站点");
dt.Columns.Add("指导教师");
dt.Columns.Add("论文题目");
foreach ( Unionstars.Thesis.ThesisInfo info in lists )
{
DataRow row = dt.NewRow();
row["学号"] = info.StudentID.Trim();
row["姓名"] = info.StudentName;
row["站点"] = info.SiteName;
row["指导教师"] = info.TeacherName;
row["论文题目"] = info.Subhead;
}
dt.Rows.Add(row);

//导出TXT文件
StringBuilder str = new StringBuilder();
for(int i=0; i<dt.Rows.Count-1; i++)
{
str.Append(i+1);
str.Append(" ");
for(int j=0; j<=dt.Columns.Count-1; j++)
{
str.Append(dt.Rows[i][j].ToString());
if(j!=dt.Columns.Count-1)
{
str.Append(" ");
}
}
str.Append("/r/n");
}
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=FileName.txt");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.text";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
Response.Write(str.ToString());
Response.End();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值