使用c#将表sql导出到.txt

时间:2014-10-15 04:04:38

标签: sql text export

我想我有一个相当简单的问题。我只需要知道如何使用asp.net或C#从sql数据库中的表中导出字段?无论如何要做到这一点都会很好。

我想我正在寻找这样的东西,但也许更简单: Export values from SQL Server to txt file

无论如何,我试图从数据库中获取值到.txt,比如在asp.net或C#中按一个按钮,根据标准(如某些日期之间,日期字段或从某个用户的特定日期,并导出一定数量的用户)。任何建议都会有所帮助。

如果我使用以下代码,我需要更改哪些内容,以便在数据库和日期列中选择某个列(如Note)时,我需要做什么?

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;  

public partial class ExportText : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MYLearningConnectionString"].ConnectionString);
        conn.Open();
        SqlDataAdapter da = new SqlDataAdapter("select * from tblUsers", conn);
        DataSet ds = new DataSet();
        da.Fill(ds);

        ExportToText(ds.Tables[0], "DataTable");


    }

    protected void ExportToText(DataTable dataTable, string fileName)
    {
        HttpContext context = HttpContext.Current;
        context.Response.Clear();
        foreach (DataColumn column in dataTable.Columns)
        {
            context.Response.Write(column.ColumnName + ",");
        }
        context.Response.Write(Environment.NewLine);

        foreach (DataRow row in dataTable.Rows)
        {
            for (int i = 0; i < dataTable.Columns.Count; i++)
            {
                context.Response.Write(row[i].ToString() + ",");
            }
            context.Response.Write(Environment.NewLine);
        }
        context.Response.ContentType = "text/csv";
        context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName + ".txt");
        context.Response.End();
    }
}

0 个答案:

没有答案