Datagrid export data to excel file in three ways

Original connection:

http://www.cnblogs.com/xieduo/articles/606202.html

Recommended connection: http://tonyqus.sinaapp.com/tutorial

 

Method One: Export to csv file , stored either on the server side path , and then to customers downloaded advantages: 1, can be carried out identity authentication after download to the customer, if placed in non-web directory is no corresponding url, customers can not feel free to download . 2, but also because the generated files, so the space occupied by the server, but the file name can be stored in the database, the customer does not need to be repeated again when downloading files generated. 3, csv file is a text file, a comma separated fields, separated by carriage return line, easy to import and export data. Implementation:  

 
 
 
 

 
 
  the SqlConnection the SqlConnection Conn new new = (System.Configuration.ConfigurationSettings.AppSettings [ "Conn"]);    the SqlDataAdapter new new DA = the SqlDataAdapter ( "SELECT * from TB1", Conn);    the DataSet the DataSet new new DS = ();    da.Fill (DS, "table1");    the DataTable ds.Tables dt = [ "table1"]; 
 
 
 
 
   string name = System.Configuration.ConfigurationSettings.AppSettings [ "downloadurl" ]. ToString () + DateTime.Today.ToString ( "yyyyMMdd") + new Random (DateTime.Now.Millisecond) .Next (10000) .ToString () + ".csv"; // stored in the web.config downloadurl path specified, the file format of the current date +4 bit random number    the FileStream new new FS = the FileStream (name, FileMode.Create, FileAccess.Write);    the StreamWriter new new SW = the StreamWriter (FS, System.Text.Encoding.GetEncoding ( "GB2312"));    sw.WriteLine ( "automatic number, name, age");    the foreach (DR in the DataRow dt.Rows)    {     sw.WriteLine (DR [ "ID" ] + "," + DR [ "vname"] + "," DR + [ "the iAge"]);    }    sw.Close ();    the Response.AddHeader ( "the Content-Disposition", "Attachment; filename =" + Server .UrlEncode (name));    Response.ContentType = "file application / MS-Excel"; // return a specified streaming client can not be read, it must be downloaded 
 
 
 
 
 
 
 
 
 
 
   Response.WriteFile (name); // file stream sent to the client    Response.End (); 

Method Two: Export to csv file, not stored in the server, the browser directly to the output file stream

Advantages: 1, generated at any time, do not need to consume resources 2, may be bonded authentication 3 also facilitate data exchange implemented method: the SqlConnection the SqlConnection Conn new new = (System.Configuration.ConfigurationSettings.AppSettings [ "Conn"]);    the SqlDataAdapter new new DA = the SqlDataAdapter ( "SELECT * from TB1", Conn);    the DataSet the DataSet new new DS = ();    da.Fill (DS, "table1");    the DataTable ds.Tables dt = [ "table1"];    the StringWriter the StringWriter new new SW = () ;    sw.WriteLine ( "automatic number, name, age");    the foreach (DR in the DataRow dt.Rows)    {     sw.WriteLine (DR [ "ID"] + "," + DR [ "vname"] + "," DR + [ "the iAge"]);    }    sw.Close ();    the Response.AddHeader ( "the Content-Disposition", "Attachment;filename=test.csv");   Response.ContentType = "application/ms-excel"; 
 
 
 

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
   Response.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312"); 
   Response.Write(sw); 
   Response.End();

Method for one or two to add that if you want to export is xls file delimiters with \ t on it, do not use commas

代码修改如下: 
sw.WriteLine("自动编号\t姓名\t年龄"); 
   foreach(DataRow dr in dt.Rows) 
   { 
    sw.WriteLine(dr["ID"]+"\t"+dr["vName"]+"\t"+dr["iAge"]); 
   } 
另外,修改输出的文件扩展名为xls即可。
 

方法三:从datagrid导出html代码,生成excel文件,给客户端下载 

优点: 
1、有固定的格式,样子好看(datagrid的样子) 

局限性: 
1、不适合数据交换,里面有html代码,比较乱,没有固定格式 
2、datagrid不能有分页、排序等,否则出错 

实现方法: 
Response.Clear(); 
   Response.Buffer= false; 
   Response.Charset="GB2312"; 
   Response.AppendHeader("Content-Disposition","attachment;filename=test.xls"); 
   Response.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");    Response.ContentType = "application/ms-excel";    this.EnableViewState = false; 
   System.IO.StringWriter oStringWriter = new System.IO.StringWriter(); 
   System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter); 
   this.DataGrid1.RenderControl(oHtmlTextWriter); 
   Response.Write(oStringWriter.ToString()); 
   Response.End();

Here to point out: Some users reflect the error code is "No dr [" id "]" and the like occur, this code is according to my data structure written to the relevant field to be replaced when your own is .

There is, if the file name needed Chinese words, such a modification Response.AddHeader ( "Content-Disposition", "attachment; filename =" + System.Web.HttpUtility.UrlEncode ( "Chinese", System.Text.Encoding.UTF8) + ".xls");

Reproduced in: https: //my.oschina.net/garyun/blog/602773

Guess you like

Origin blog.csdn.net/weixin_34352005/article/details/91774676