0
我想導出數據集以使用以下代碼從asp.net頁面方法(webmethod)導出excel。導出數據集以使用asp.net從webmethod導出excel的問題
[WebMethod]
public static void ExporttoExcel()
{
DataSet ds;
productfactory pf=new productfactory();
ds = pf.getproducts();
HttpResponse response = HttpContext.Current.Response;
// first let's clean up the response.object
response.Clear();
response.Charset = "";
response.ContentEncoding = System.Text.Encoding.Default;
// set the response mime type for excel
response.ContentType = "application/vnd.ms-excel";
response.AddHeader("Content-Disposition", "attachment;filename=\"products.xls\"");
// create a string writer
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// instantiate a datagrid
DataGrid dg = new DataGrid();
dg.DataSource = ds.Tables[0];
dg.DataBind();
dg.RenderControl(htw);
string filepath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\products.xls";
response.Write(sw.ToString());
// response.End();
}
}
}
上面的代碼似乎是工作以外的事情,下載文件對話框沒有打開詢問用戶「保存」 /「打開」對話框,因此我沒有看到響應是否被寫入OK到一個文件。相反,當我在Firebug中檢查響應時,我得到了HTML表格結構中的數據。
請問有人可以幫我嗎?
謝謝。