我从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

有人能帮我吗?

推荐答案

A DataSet已经是contains DataTables了.你可以使用:

DataTable firstTable = dataSet.Tables[0];

或按姓名:

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

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

using (SqlConnection conn = ...)
{
    // Code here...
}

Asp.net相关问答推荐

JWT 和 Google 在 Razor 页面中进行身份验证和授权

InvalidOperationException:在程序集上找不到UserSecretsIdAttribute

如何在 ASP.NET 中设置自动实现属性的默认值

如何使多行的 TextBox 控件无法调整大小?

jquery 1.9.0 和 modernizr 无法使用 ASP.NET Web 优化框架进行缩小

在控制器 asp.net mvc 5 的视图上显示错误消息

等待本地主机,永远!

最佳服务器端 .NET PDF 编辑库

免费的 ASP.Net 和/或 CSS 主题

每个 'HttpRequest' 在 ASP.NET 中都有自己的线程吗?

发布网站项目时临时路径太长

如何在 ASP.NET 中通过 LAN 访问您的网站

由 UpdatePanel 内 GridView 内的 LinkBut​​ton 触发的完整回发

如何从 ASP.NET 中的数据表/数据视图中 Select 前 n 行

删除 HTML 或 ASPX 扩展

如何使用restsharp下载文件

如何获取程序集的最后修改日期?

IronRuby死了吗?

重新生成designer.cs

Application_End global.asax