【发布时间】:2012-02-17 11:45:21
【问题描述】:
我正在从 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
谁能帮帮我?
【问题讨论】: