将数据库中的所有详细信息存储到文件中,然后下载该文件

时间:2011-09-21 04:26:55

标签: c# asp.net sql-server-2008 download

protected void btnDownload_Click(object sender, EventArgs e)
{
    SqlCommand Command = connection.CreateCommand();
                    SqlDataReader SQLRD;
                    Command.CommandText = "Select *from Attendance";
                   connection.Open();
        SQLRD = Command.ExecuteReader();            
        string data = "";
          while (SQLRD.Read())
        {
            data += SQLRD[0].ToString();
            data += SQLRD[1].ToString();

        }

        SQLRD.Close();
        connection.Close();

        string filename = @"C:\download.csv";
        FileStream fs = new FileStream(filename,FileMode.Append, FileAccess.Write);
        StreamWriter sw = new StreamWriter(fs);
        sw.WriteLine(data);
        sw.Flush();
        sw.Close();
        fs.Close();    }

这是我到目前为止所拥有的。我想将上述查询中的所有数据存储在一个文件中。该文件将被下载。

5 个答案:

答案 0 :(得分:1)

protected void btnDownload_Click(object sender, EventArgs e)
{
   MySqlConnection connection = new MySqlConnection(@"Data Source=localhost\SQLEXPRESS;Initial Catalog=PSeminar;Integrated Security=true;Trusted_Connection=Yes;MultipleActiveResultSets=true");

   MySqlCommand myCommand = myConn.CreateCommand();
   MySqlDataReader SQLRD;
   myCommand.CommandText = "SELECT * FROM Attendance";
   connection.Open();
   SQLRD = myCommand.ExecuteReader();
   string data="";
   while (SQLRD.Read())
   {
     data += "Row data, arrange how you want";//SQLRD[0].Tostring();-->first coloum
   }
   SQLRD.Close();
   connection.Close();

   string filename = "F:\file1.txt";  //with path
   FileStream fs = new FileStream(filename, FileMode.Append, FileAccess.Write);
   StreamWriter sw = new StreamWriter(fs);
   sw.WriteLine(data);
   sw.Flush();
   sw.Close();
   fs.Close();
}

已编辑的代码:只需在代码中复制粘贴并更改文件名路径

即可
            MySqlCommand Command = connection.CreateCommand();
            connection.Open();
            //SqlCommand Command = new SqlCommand();
            MySqlDataReader SQLRD;
            Command.CommandText = "Select * from Attendance";
            //connection.Open();
            SQLRD = Command.ExecuteReader();
            string data = "";
            while (SQLRD.Read())
            {
                data += SQLRD[0].ToString()+"\n";
                data += SQLRD[1].ToString()+"\n";

            }

            SQLRD.Close();
            connection.Close();

            string filename = @"F:\download.csv";
            FileStream fs = new FileStream(filename, FileMode.Append, FileAccess.Write);
            StreamWriter sw = new StreamWriter(fs);
            sw.WriteLine(data);
            sw.Flush();
            sw.Close();
            fs.Close();
        }

答案 1 :(得分:1)

将数据保存到文件的代码将根据所需的文件格式进行更改。保存文件后,使用HttpResponse.TransmitFile将文件推送到浏览器。例如,模板代码为

protected void btnDownload_Click(object sender, EventArgs e)
{
   SqlConnection connection = new SqlConnection(@"Data Source=localhost\SQLEXPRESS;Initial Catalog=PSeminar;Integrated Security=true;Trusted_Connection=Yes;MultipleActiveResultSets=true");

   string query = "SELECT * FROM Attendance";

   // Fetch data using data reader or data adapter
   ...

   // Save the data to file in required format
   string filePath;
   ....

   // Push the file from response
   Response.ContentType = "text/csv"; // set as per file type e.g. text/plain, text/xml etc
   Response.AddHeader("Content-Disposition", "attachment;filename=myfilename.csv"); // will prompt user for save file dialog, use inline instead of attachment to suppress the dialog
   Response.TransmitFile(filePath);
}

有关以某种格式存储文件的代码,请参阅其他答案,例如xml / csv。

答案 2 :(得分:0)

使用序列化可以获得最佳效果。我会使用Active Record设计模式创建一个结构化对象。

然后我将使用XML Serialization将该对象输出到XML对象。然后我会将该XML保存到磁盘并稍后对其进行反序列化并使用它,就像没有发生任何事情一样。

请参阅:How to serialize and object to XML in C# on MSDN

答案 3 :(得分:0)

写入文件的最简单方法是使用DataTable.WriteXml方法将数据表的整个数据写入XML文件,稍后可以下载此文件:

SqlDataAdapter sqlAdap = new SqlDataAdapter(query, connection);
DataTable dt = new DataTable();
sqlAdap.Fill(dt);

string filePath = Server.MapPath("~/filename.xml");
dt.WriteXml(filePath);

但是如果你想把这些数据写成某种特定的格式,比如csv,你必须循环遍历所有的行,并使用StreamWrite类将它写入文件。下面的代码只是为了给你一个想法,我没有添加任何类型检查或检查null。

string filePath = Server.MapPath("~/somefile.csv");
System.IO.StreamWriter sw = new System.IO.StreamWriter(filePath);

foreach (DataRow r in dt.Rows)
{
        for (int i = 0; i < dt.Columns.Count; i++)
        {
             sw.Write(r[i].ToString());
             sw.Write(",");
        }

        sw.WriteLine();
}
sw.Close();

答案 4 :(得分:0)

您可以将其作为DataSet导出到磁盘,如下所示:

using (var conn = new SqlConnection(@"<your conn str>"))
{
    var ds = new DataSet();
    using (var invoiceCmd = conn.CreateCommand())

    //One of these per table to export
    using(var invoiceAdapter = new SqlDataAdapter(invoiceCmd))
    {
        invoiceCmd.CommandText = "SELECT * FROM Attendance";
        invoiceAdapter.Fill(ds, "Attendance");
    }

    ds.WriteXml(@"C:\temp\foo.xml");
}