所以只要將查詢結果轉出到 DataGrid,就可以完成我們的目的。
首先,我們必須先在 WebForm 中新增一個DataGrid,由於我們希望透過DataGrid來存放查詢結果,而將來所產生的的Excel模樣又跟這
DataGrid有關係,也就是這裡的DataGrid樣子長怎樣,將來的Excel就會長怎樣。然而,有可能不希望這DataGrid出現在使用者的眼前,
這簡單,只要我們在程式的最後面將 DataGrid的 Visible 設成 false 就可以解決。範例如下:
private
void Button1_Click(object
sender, System.EventArgs e)
{
System.Configuration.AppSettingsReader app =
new
System.Configuration.AppSettingsReader();
string
ConnectionString=(string)app.GetValue("DBConnectionString",typeof(string));
string sql=@"
select * from Customers;
";
SqlConnection conn =
newSqlConnection(ConnectionString);
SqlCommand sqlCmd =
newSqlCommand(sql, conn);
conn.Open();
DataSet ds=
newDataSet();
SqlDataAdapter oDataAdapter =
newSqlDataAdapter(sqlCmd);
oDataAdapter.Fill(ds, 0, 0, "Table1");
conn.Close();
dg1.Visible=
true;dg1.DataSource=ds;
dg1.DataBind();
Response.Clear();
Response.AddHeader( "Content-Disposition",
"attachment;filename=VisitReport.xls" );
Response.ContentType = "application/vnd.ms-excel";
Response.ContentEncoding=System.Text.Encoding.GetEncoding("Big5");
Response.Write("<html><body>");
ResponseReportOnly(dg1 );
Response.Write("</body></html>");
Response.End();
dg1.Visible=
false;
}
private
void
ResponseReportOnly(System.Web.UI.WebControls.DataGrid dg)
{
dg.HeaderStyle.CssClass="TblHeader_Prn";
dg.ItemStyle.CssClass="TblOddRow_Prn";
dg.AlternatingItemStyle.CssClass = "TblEvenRow_Prn";
TextWriter tw=
newStringWriter();
HtmlTextWriter hw =
newHtmlTextWriter( tw );
tw.Write( "<div align=center>" + "2005 ADOC Week" + "</div>");
dg.RenderControl( hw );
// 用來自動產生 Excel 檔,如果 User 不希望自動產生,可以拿掉
string
newFilePath=Server.MapPath("tt.xls");
FileStream fs=
newFileStream(newFilePath,FileMode.Create,FileAccess.ReadWrite,FileShare.ReadWrite);
StreamWriter sw=
newStreamWriter(fs,System.Text.Encoding.Default);
sw.Write(tw.ToString());
sw.Close();
fs.Close();
Response.Write(tw.ToString());
}
沒有留言:
張貼留言