DataSet转Excel
public void DataSetToExcel(DataSet ds, string fileName)
{
try
{
HttpResponse response;
response = HttpContext.Current.Response;
response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
response.Charset = "utf-8";
response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
response.ContentType = "application/vnd.ms-excel";//application/vnd.ms-excel 方式则需要自己设置客户端浏览器读取Excel的格式,此处采取默认方式
System.Web.UI.HtmlTextWriter htmlWriter = null;
System.Web.UI.WebControls.DataGrid dgExport = null;
StringWriter sft = new StringWriter();
System.Data.DataTable dt = ds.Tables[0];
htmlWriter = new System.Web.UI.HtmlTextWriter(sft);
dgExport = new System.Web.UI.WebControls.DataGrid();
dgExport.DataSource = dt.DefaultView;
dgExport.AllowPaging = false;
dgExport.DataBind();
dgExport.RenderControl(htmlWriter);
response.Write(sft);
response.End();
}
catch (Exception ex)
{
throw ex;
}
}