Asp.net export to CSV file garbled

Source: Internet
Author: User

Http://social.microsoft.com/Forums/zh-CN/295/thread/14a833f5-95bf-48ef-b6cf-c6028f338561

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 ();

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.