我正在尝试使用以下代码将数据集从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();
}
}
}
上面的代码似乎工作正常,除了下载文件对话框没有打开以询问用户是否“保存”/“打开”对话框,因此我没有看到响应被写入文件。相反,当我在Firebug中检查响应时,我将以HTML表格结构获取数据。
有人可以帮我吗?
感谢。
答案 0 :(得分: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();
}