【转自】 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();