我从SQL表中检索数据,以便可以在页面上以HTML表的形式显示结果.稍后,我需要能够将该表另存为CSV文件.
到目前为止,我已经想出了如何检索数据并将它们填充到用于显示目的的数据集中(它工作得很好)……
string selectQuery = "SELECT Name, ProductNumber, ListPrice FROM Poduction.Product";
// Establish the connection to the SQL database
SqlConnection conn = ConnectionManager.GetConnection();
conn.Open();
// Connect to the SQL database using the above query to get all the data from table.
SqlDataAdapter myCommand = new SqlDataAdapter(selectQuery, conn);
// Create and fill a DataSet.
DataSet ds = new DataSet();
myCommand.Fill(ds);
以及如何通过以下代码将它们保存在CSV文件中:http://www.evontech.com/login/topic/1983.html
private void exportDataTableToCsv(DataTable formattedDataTable, string filename)
{
DataTable toExcel = formattedDataTable.Copy();
HttpContext context = HttpContext.Current;
context.Response.Clear();
foreach (DataColumn column in toExcel.Columns)
{
context.Response.Write(column.ColumnName + ",");
}
context.Response.Write(Environment.NewLine);
foreach (DataRow row in toExcel.Rows)
{
for (int i = 0; i < toExcel.Columns.Count; i++)
{
context.Response.Write(row.ToString().Replace(",", string.Empty) + ",");
}
context.Response.Write(Environment.NewLine);
}
context.Response.ContentType = "text/csv";
context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + ".csv");
context.Response.End();
}
现在我的问题是如何将DataSet
转换成DataTable
?我试过这里描述的方法,幸运NO:http://www.ezineasp.net/post/ASP-Net-C-sharp-Convert-DataSet-to-DataTable.aspx
有人能帮我吗?