2010-08-06 63 views
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表格结构中的数据。

请问有人可以帮我吗?

谢谢。

回答

0

如果你能得到你的产品数据转换成一个DataTable,而不是尝试以下操作:

protected void ExportToExcel(DataTable myTable, string name) 
    { 
     //Set Response 
     Response.Clear(); 
     Response.AddHeader("content-disposition", "attachment; filename="+name+".xls"); 
     Response.Charset = ""; 
     Response.ContentType = "application/vnd.ms-excel"; 

     //Print columns headers 
     //manually create column headers 
     Response.Write("Column1" + "\t"); 
     Response.Write("Column2" + "\t"); 
     Response.Write("\n"); 

     foreach (DataRow row in myTable.Rows) // Loop over the rows. 
     { 
      Response.Write(row["column1_database_name"].ToString() + "\t"); 
      Response.Write(row["column2_database_name"].ToString() + "\t"); 
      Response.Write("\n"); 
     } 

     //End Response 
     Response.End(); 
    }