. Net Excel export function,. net excel Export
Read data from the database and export it to an Excel file
Void btnExport_Click (object sender, EventArgs e) {IList <string> fields = new List <string> (); IList <string> headers = new List <string> (); fields. add ("database field name 1"); headers. add ("Excel Field name 1"); fields. add ("database field name 2"); headers. add ("Excel Field name 2"); StringBuilder strFlag = new StringBuilder (); foreach (string head in headers) {strFlag. append (head + ","); if (head = headers [headers. count-1]) {strFlag = strFl Ag. remove (strFlag. length-1, 1); strFlag. append ("\ r \ n") ;}} DataSet dt = new DataSet (); // obtain data from the database if (dt! = Null & dt. tables [0]. rows. count> 0) {foreach (DataRow row in dt. tables [0]. rows) {foreach (string field in fields) {strFlag. append (row [field]). append (","); if (field = fields [headers. count-1]) {strFlag = strFlag. remove (strFlag. length-1, 1); strFlag. append ("\ r \ n") ;}} Page. response. clear (); Page. response. buffer = false; Page. response. charset = "GB2312"; Page. response. appendHeader ("Content-Disposition", "attachment?filename=excelfile name .csv"); Page. response. contentType = "application/octet-stream"; Page. response. contentEncoding = System. text. encoding. getEncoding ("GB2312"); Page. enableViewState = false; Page. response. write (strFlag. toString (); Page. response. end ();}}