示例图片:
示例代码:
private DataSet ds = new DataSet();
protected void Page_Load(object sender, EventArgs e)
{
string Str = "Initial Catalog=Northwind;Data Source=localhost;Integrated Security=SSPI;";
SqlConnection con = new SqlConnection(Str);
SqlDataAdapter da = new SqlDataAdapter("select EmployeeID,LastName,FirstName,Title from Employees", con);
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();
if (ds.Tables[0].Rows.Count > 0)
{
int i = 0;
for (int n = 0; n < ds.Tables[0].Rows.Count; n++)
{
for (int m = 0; m < ds.Tables[0].Columns.Count; m++)
{
i++;
sb.Append(ds.Tables[0].Rows[n][m].ToString());
if (i % 4 != 0)
{
sb.Append(",");
}
else
{ break; }
}
sb.Append("/r/n");
}
Page.Response.Clear();
Page.Response.Buffer = true;
Page.Response.Charset = "GB2312";
Page.Response.AppendHeader("Content-Disposition", "attachment;filename=abc.txt");
Page.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");//设置输出流为简体中文
Response.ContentType = "text/plain";//设置输出文件类型为txt文件。
this.EnableViewState = false;
System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN", true);
System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad);
Page.Response.Write(sb.ToString());
Page.Response.End();
}
}