首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > asp.net >

怎么将数据导出为excel?请好心大侠们帮忙

2011-12-14 
如何将数据导出为excel?请好心大侠们帮忙//将datagrid做为数据流输出.public string grid(int page,string

如何将数据导出为excel?请好心大侠们帮忙
//将datagrid做为数据流输出.
public string grid(int page,string name)
{
......
return s;//s是一个表格.
}
//导出代码:
this.grid(0,name); //0表示不分页 
Response.Clear(); 
Response.Buffer= true; 
Response.Charset="GB2312";  
Response.AppendHeader("Content-Disposition","attachment;filename=FileName.xls"); 
Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。 
this.EnableViewState = false;  
System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad); 
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
Response.Write(s.ToString());
Response.End();
提示:String 引用没有设置为 String 的实例。
参数名: s 


[解决办法]

C# code
        public static void Download_Excel(DataTable dt,string filename)        {            System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");            System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(filename + ".xls"));            string str_column = "";            string ls_item = "";            int i = 0;            foreach(DataColumn dc in dt.Columns)            {                str_column += "\t" + dc.ColumnName;            }            str_column = str_column.Remove(0,1) + "\n";            System.Web.HttpContext.Current.Response.Write(str_column);            foreach(DataRow row in dt.Rows)             {                 //在当前行中,逐列获得数据,数据之间以\t分割,结束时加回车符\n                 for(i=0;i<(dt.Columns.Count-1);i++)                     ls_item +=row[i].ToString().Replace("\"","“") + "\t";                      ls_item += row[i].ToString().Replace("\"","“") +"\n";                 //当前行数据写入HTTP输出流,并且置空ls_item以便下行数据                     System.Web.HttpContext.Current.Response.Write(ls_item);                 ls_item="";             }            System.Web.HttpContext.Current.Response.End();        }
[解决办法]

导出EXCEL表
/////////////////////////////////////////////////////////////////////////////
System.Web.UI.WebControls.DataGrid dgr = new DataGrid();
dgr.DataSource = dt;
dgr.DataBind();
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + "" + DateTime.Now.ToShortDateString() +""+".xls"+"");
HttpContext.Current.Response.Charset = "gb-2312"; 
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default; 
HttpContext.Current.Response.ContentType = "application/ms-excel/ms-word"; 
System.IO.StringWriter tw = new System.IO.StringWriter() ; 
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
dgr.RenderControl(hw);
dgr.Dispose();
HttpContext.Current.Response.Write(tw.ToString()); 
HttpContext.Current.Response.End();
[解决办法]
http://www.ebookit.cn/177.html

热点排行