DataSet导出到Excel比较完整的解决方案(一)--客户端生成文件(downmoon)
2009-01-16 10:19:16 来源:WEB开发网有一客户需求:
1、要从SQL Server数据库导出并生成Excel ;
2、用户下载对应的Excel并填写上传再导入到SQL server。
费了将近六个小时,故一定要把过程写下来,希望看到此文的朋友少走些不必要的弯路。
首先,想到的是直接导出到客户端,代码如下:
DataSetToExcel
public static void DataSetToExcel(DataSet oDS, HttpResponse Response, string fileName)
{
if (oDS == null || oDS.Tables[0] == null || oDS.Tables[0].Rows.Count == 0) { return; }
Response.Clear();
//Encoding pageEncode = Encoding.GetEncoding(PageEncode);
HttpContext.Current.Response.Charset = "gb2312";
//Response.ContentType = "application/vnd-excel";//"application/vnd.ms-excel";
//Response.ContentType = "application/x-octet-stream";//"application/vnd.ms-excel";
Response.ContentType = "text/csv";//"application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName + ".cvs");
System.IO.StringWriter oSW = new System.IO.StringWriter();
HtmlTextWriter oHW = new HtmlTextWriter(oSW);
DataGrid dg = new DataGrid();
dg.DataSource = oDS.Tables[0];
dg.DataBind();
dg.RenderControl(oHW);
Response.Write(oSW.ToString());
Response.Flush();
Response.Close();
}
赞助商链接