我在 SQL Server 2000 中有数据,并且有一个超链接,它转到一个传递表单,其代码隐藏将数据输出到 Excel 文件。我一直在关注本教程:
http://www.dzone.com/links/r/export_gridview_to_excelcsv_in_net_using_c.html
我已经成功地从 DataReader 输出了一些样本值。我遇到的第一个问题是 1.1 中没有 DataTable Load 方法。我有通过 DataReader 返回的数据,但我需要帮助的是如何创建标题并将它们与数据行一起输出到 Excel 文件......
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.Buffer = true;
string attachment
= "attachment;filename=Report_" + DateTime.Now.ToString() + ".xls";
Response.AddHeader("content-disposition", attachment);
Response.Charset = string.Empty;
Response.Cache.SetCacheability(System.Web.HttpCacheability.Public);
Response.ContentType = "application/ms-excel";
DataTable dt = new DataTable();
dt.Columns.Add("Company");
dt.Columns.Add("Address1");
dt.Columns.Add("Address2");
dt.Columns.Add("City");
dt.Columns.Add("State");
dt.Columns.Add("ZipCode");
SqlConnection con = new SqlConnection();
SqlCommand com = new SqlCommand();
con.ConnectionString = "myconnstring";
com.Connection = con;
com.CommandText
= "SELECT DISTINCT Company, Address1, Address2, City, State, ZipCode" +
" FROM Vendor_View";
con.Open();
SqlDataReader dr = com.ExecuteReader();
while(dr.Read())
{
// how to grab and output data to Excel?
}