String name = System. Configuration. ConfigurationSettings. deleettings ["downloadurl"]. ToString ();
FileStream fs = new FileStream (name, FileMode. Create, FileAccess. Write );
StreamWriter sw = new StreamWriter (fs, System. Text. Encoding. GetEncoding ("gb2312 "));
Sw. WriteLine ("automatic number, name, age ");
Foreach (DataRow dr in dt. Rows)
{
Sw. WriteLine (dr ["ID"] + "," + dr ["vName"] + "," + dr ["iAge"]);
}
Sw. Close ();
Response. AddHeader ("Content-Disposition", "attachment; filename =" + Server. UrlEncode (name ));
Response. ContentType = "application/ms-excel"; // specify that the returned stream cannot be read by the client and must be downloaded.
Response. WriteFile (name); // send the file stream to the client
Response. End ();
Highlighted in red!
------
String strFile = "FileName" + DateTime. Now. ToString ("yyyyMMddhhmmss") + ". csv ";
// Replace this part with the content obtained from the DataTable/GridView.
StringBuilder sb = new StringBuilder ();
Sb. AppendLine ("id, name ");
Sb. AppendLine ("1, Jun juncai ");
Sb. AppendLine ("2, ");
Sb. AppendLine ("3, Jon ");
StringWriter sw = new StringWriter (sb );
Sw. Close ();
Response. AddHeader ("Content-Disposition", string. Format ("attachment; filename = {0}", strFile ));
Response. Charset = "gb2312 ";
Response. ContentType = "application/ms-excel ";
Response. ContentEncoding = System. Text. Encoding. GetEncoding ("gb2312 ");
Response. Write (sw );
Response. Flush ();
Response. End ();