Alw*_*ice 37 html c# sql asp.net
我正在从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);
Run Code Online (Sandbox Code Playgroud)
以及如何使用以下代码将其保存在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();
}
Run Code Online (Sandbox Code Playgroud)
现在我的问题是如何将其转换DataSet
为DataTable
?我试过这里所描述的方式没有运气:http://www.ezineasp.net/post/ASP-Net-C-sharp-Convert-DataSet-toANNTable.aspx
谁能帮我?
Jon*_*eet 107
一个DataSet
已经包含 DataTables
.你可以使用:
DataTable firstTable = dataSet.Tables[0];
Run Code Online (Sandbox Code Playgroud)
或按名称:
DataTable customerTable = dataSet.Tables["Customer"];
Run Code Online (Sandbox Code Playgroud)
请注意,您应该拥有using
SQL代码的语句,以确保正确处理连接:
using (SqlConnection conn = ...)
{
// Code here...
}
Run Code Online (Sandbox Code Playgroud)
DataSet是DataTables的集合。...您可以从DataSet中获取数据表,如下所示。
//here ds is dataset
DatTable dt = ds.Table[0]; /// table of dataset
Run Code Online (Sandbox Code Playgroud)