Asp.net girdview export .csv format

Source: Internet
Author: User

/// <Summary>
/// Export to. CSV format
/// </Summary>
/// <Param name = "GV"> gridview Control </param>
/// <Param name = "page"> page </param>
/// <Param name = "FILENAME"> file name </param>
Public static void importtocsv (system. Web. UI. webcontrols. gridview GV, system. Web. UI. Page, int [] displaycolumns, string filename)
{
String defaultfilename = "input name.csv ";
If (string. isnullorempty (filename ))
{
Filename = defaultfilename;
}
Stringbuilder sb = new stringbuilder ();
Page. response. appendheader ("content-disposition", "attachment; filename =" + filename );
// Page. response. contenttype = "application/MS-excel ";
Page. response. charset = "UTF-8 ";
Page. response. contentencoding = system. Text. encoding. utf8;

Foreach (system. Web. UI. webcontrols. gridviewrow row in GV. Rows)
{
If (row. rowtype = system. Web. UI. webcontrols. datacontrolrowtype. datarow)
{
For (INT I = 0; I <displaycolumns. length; I ++)
{
// & Nbsp; has instead of string. Empty when default value is string. empty in the cell of gridview, so replace it.
SB. append ("\"");
If (! Row. cells [displaycolumns [I]. Text. Trim (). Equals ("& nbsp ;"))
{
SB. append (row. cells [displaycolumns [I]. Text. Trim ());
}
SB. append ("\"");
If (I! = Displaycolumns. Length-1)
{
SB. append (",");
}
Else
{
SB. append ("\ r \ n ");
}
}
}
}

// Output
Page. response. Write (sb. tostring ());
Page. response. End ();
}

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.