一尘不染

如何将DataSet转换为DataTable

sql

我正在从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();
    }

现在我的问题是如何将其转换DataSetDataTable?我尝试过这里描述的方法,但是 没有
运气:http : //www.ezineasp.net/post/ASP-Net-C-sharp-Convert-DataSet-to-
DataTable.aspx

谁能帮我?


阅读 231

收藏
2021-03-17

共1个答案

一尘不染

一个DataSet已经 包含 DataTables。您可以使用:

DataTable firstTable = dataSet.Tables[0];

或按名称:

DataTable customerTable = dataSet.Tables["Customer"];

请注意,您应该具有using用于SQL代码的语句,以确保正确处理连接:

using (SqlConnection conn = ...)
{
    // Code here...
}
2021-03-17