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(); }这就是我到目前为止所拥有的。我希望将上述查询的所有数据存储在一个文件中。此文件将被下载。
发布于 2011-09-21 13:21:25
将数据保存到文件的代码将根据所需的文件格式进行更改。保存文件后,使用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等格式存储文件的代码,请参阅其他答案。
https://stackoverflow.com/questions/7494611
复制相似问题