This is an example used by a friend in development. It is used to save exported data to an excel table. If you need it, please wait for a reference.
| The Code is as follows: |
Copy code |
Public static void TableToExcel (System. Data. DataTable dt, string fileType) { System. IO. StringWriter sw = new System. IO. StringWriter (); System. Text. StringBuilder sb = new System. Text. StringBuilder (); If (fileType. Equals ("xls ")) { Foreach (System. Data. DataColumn col in dt. Columns) { Sb. Append (col. ColumnName + "t "); } Sw. WriteLine (sb. ToString ()); } Foreach (System. Data. DataRow row in dt. Rows) { Sb = new System. Text. StringBuilder (); Foreach (System. Data. DataColumn col in dt. Columns) { Sb. Append (row [col. ColumnName]. ToString (). Replace (Environment. NewLine, ""). Replace ("t", "") + "t "); } Sw. WriteLine (sb. ToString ()); } Sw. Close (); String fileName = (dt. TableName ?? "Data") + (fileType. Equals ("xls ")? ". Xls": ". txt "); System. Web. HttpResponse response = System. Web. HttpContext. Current. Response; Response. Clear (); Response. Buffer = true; Response. Charset = "gb2312 "; Response. AddHeader ("Content-Disposition", "attachment; filename =" + fileName ); Response. ContentType = fileType. Equals ("xls ")? "Application/ms-excel": "text/plain "; Response. ContentEncoding = System. Text. Encoding. GetEncoding ("gb2312 "); Response. Write (sw ); Response. End (); } |