C#中操作Excel的方法很多,这里通过Response输出流的方式导到浏览器端成excel文件。
方法代码:
public void ExportResult(DataSet ds,string excelName)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.ContentType = "application/vnd.ms-xls";
StringWriter stringWrite = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
DataGrid dg = new DataGrid();
dg.DataSource = ds;
dg.DataBind();
dg.RenderControl(htmlWrite);
HttpContext.Current.Response.AddHeader
("content-disposition", "attachment;filename="+HttpUtility.UrlEncode(excelName))
HttpContext.Current.Response.Write(stringWrite.ToString());
HttpContext.Current.Response.End();
}