日期:2014-05-20  浏览次数:20437 次

有一种DataGrid到Excel的方法,大家有没有现成的函数可用(立即揭帖)
找了个由Datagrid导出到Excel的代码,也实现了导出功能,但是我想把它封装成一个可用的函数形式,哪位前辈有,或者用过?万分感谢!

我找到的代码如下:
————————————————————————————
  //导出到Excel功能代码实现
SqlConnection   conn=new   SqlConnection(System.Configuration.ConfigurationSettings.AppSettings[ "ConnectionSqlServer "].ToString());  
SqlDataAdapter   da=new   SqlDataAdapter( "select   LastName,FirstName,TitleOfCourtesy,Extension   from   Employees ",conn);  
DataSet   ds=new   DataSet();  
da.Fill(ds, "table1 ");  

DataTable   dt=ds.Tables[ "table1 "];  

StringWriter   sw=new   StringWriter();  
sw.WriteLine( "姓名\t姓\t称谓\t数字 ");  
foreach(DataRow   dr   in   dt.Rows)  
{  
sw.WriteLine(dr[ "LastName "]+ "\t "+dr[ "FirstName "]+ "\t "+dr[ "TitleOfCourtesy "]+ "\t "+dr[ "Extension "]);  
}  
sw.Close();  
Response.AddHeader( "Content-Disposition ",   "attachment;   filename=test.xls ");  
Response.ContentType   =   "application/ms-excel ";  
Response.ContentEncoding=System.Text.Encoding.GetEncoding( "GB2312 ");  
Response.Write(sw);  
Response.End();  

——————————————————————————————————

------解决方案--------------------
public static void ExportExcel(DataGrid rp, string strFileName) { strFileName = System.Web.HttpUtility.UrlEncode(strFileName,System.Text.Encoding.UTF8); System.Web.HttpContext.Current.Response.Clear(); System.Web.HttpContext.Current.Response.Buffer = true; System.Web.HttpContext.Current.Response.Charset = "gb2312 "; System.Web.HttpContext.Current.Response.AppendHeader( "Content-Disposition ", "online; filename= " + strFileName + ".xls "); System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding( "gb2312 "); System.Web.HttpContext.Current.Response.ContentType = "application/ms-excel "; System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo( "zh-CN ",true); System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad); System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter); rp.RenderControl(oHtmlTextWriter); rp = null; System.Web.HttpContext.Current.Response.Write(oStringWriter.ToString().Replace( " <td ", " <td STYLE= 'MSO-NUMBER-FORMAT:\\@ ' ")); System.Web.HttpContext.Current.Response.Buffer = false; System.Web.HttpContext.Current.Response.End(); }
------解决方案--------------------
编码问题
把web.config里卖的utf-8 改成gb2312
就可以了.
------解决方案--------------------
因为没有数据,所以乱码.

没有数据的时候没有足够的信息让Excel判断出编码的方式来正确显示.


所以没数据的时候有时候经常要乱码,有一行数据的时候有时候乱码,2行的时候偶尔乱码,10行以上我没见过还有这情况的.


这是Excel的原因. 如果你用记事本打开那个Excel文件,里面不乱码,那么基本上就是因为我说的原因了,是这种导出方式不可克服的(但是有什么必要导出一个空的内容呢?干吗不干脆做个模板给人下载得了....)