首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将数据库中的所有详细信息存储到一个文件中,然后下载该文件

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

Stack Overflow用户
提问于 2011-09-21 12:26:55
回答 5查看 225关注 0票数 2
代码语言:javascript
复制
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();    }

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

EN

Stack Overflow用户

发布于 2011-09-21 13:21:25

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

代码语言:javascript
复制
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等格式存储文件的代码,请参阅其他答案。

票数 1
EN
查看全部 5 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7494611

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档