生成TXT下载并以逗号分隔

 

 

前台

<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="导出TXT" />

 后台

    protected void Button1_Click(object sender, EventArgs e)
    {        
        ////导成txt
        string sqlJiu = "select Phonenumber from Phonenumber";
        SqlConnection con = Class1.DBconnection();
        SqlDataAdapter da = new SqlDataAdapter(sqlJiu, con); 
        DataSet ds = new DataSet(); 
        da.Fill(ds);
        System.Text.StringBuilder sb = new System.Text.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 % 11 != 0) 
                    { 
                        sb.Append(","); 
                    } 
                    else 
                    { break; } 
                } 
                sb.Append("\r\n"); 
            } 
            Page.Response.Clear(); 
            Page.Response.Buffer = true; 
            Page.Response.Charset = "GB2312"; 
            Page.Response.AddHeader("Content-Disposition", "attachment;filename=" + Server.UrlEncode("手机号码" + string.Format("{0:yyyyMMddHHmmss}", System.DateTime.Now) + ".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(); 
        } 
        con.Close(); 


 

      }

 

 

 

 

posted @ 2012-05-10 15:36  Q玲珑  阅读(400)  评论(0编辑  收藏  举报