C # export data in datatable to a CSV file

Source: Internet
Author: User
Tags file info

In the previous blog [C # methods for reading CSV files], I introduced how to read data from CSV files, now I will introduce how to export data from a able to a CSV file.

The code of the deme program is as follows:

Protected void button#click (Object sender, eventargs E)
{
Datatable dt = new datatable ();
DT. Columns. Add ("test1 ");
DT. Columns. Add ("Test2 ");
DT. Columns. Add ("test3 ");
DT. Columns. Add ("test4 ");
DT. Columns. Add ("test5 ");
For (INT I = 0; I <6; I ++)
{
DT. Rows. Add ();
DT. Rows [I] [0] = "cn" + I. tostring ();
DT. Rows [I] [1] = "en" + I. tostring ();
DT. Rows [I] [2] = "JN" + I. tostring ();
DT. Rows [I] [3] = "HK" + I. tostring ();
DT. Rows [I] [4] = "tw" + I. tostring ();
}

Exportdatagridtocsv (DT );

}

/// <Summary>
/// Export the data from datatable to CSV file
/// </Summary>
/// <Param name = "Grid"> </param>
Public void exportdatagridtocsv (datatable DT)
{
String strfile = "";
String Path = "";

// File info Initialization
Strfile = "test ";
Strfile = strfile + datetime. Now. tostring ("yyyymmddhhmmss ");
Strfile = strfile + ". CSV ";
Path = server. mappath (strfile );

System. Io. filestream FS = new filestream (path, system. Io. filemode. Create, system. Io. fileaccess. Write );
Streamwriter Sw = new streamwriter (FS, new system. Text. unicodeencoding ());
// Tabel Header
For (INT I = 0; I <DT. Columns. Count; I ++)
{
Sw. Write (Dt. Columns [I]. columnname );
Sw. Write ("\ t ");
}
Sw. writeline ("");
// Table body
For (INT I = 0; I <DT. Rows. Count; I ++)
{
For (Int J = 0; j <DT. Columns. Count; j ++)
{
Sw. Write (delquota (Dt. Rows [I] [J]. tostring ()));
Sw. Write ("\ t ");
}
Sw. writeline ("");
}
Sw. Flush ();
Sw. Close ();

Downloadfile (PATH );
}

Private bool downloadfile (string _ filename)
{
Try
{
System. Io. filestream FS = system. Io. file. openread (_ filename );
Byte [] filedata = new byte [fs. Length];
FS. Read (filedata, 0, (INT) fs. Length );
Response. Clear ();
Response. addheader ("Content-Type", "application/Notepad ");
String filename = system. Web. httputility. urlencode (system. Text. encoding. utf8.getbytes (_ filename ));
Response. addheader ("content-disposition", "inline; filename =" + system. Convert. tochar (34) + filename + system. Convert. tochar (34 ));
Response. addheader ("Content-Length", FS. length. tostring ());
Response. binarywrite (filedata );
FS. Close ();
System. Io. file. Delete (_ filename );
Response. Flush ();
Response. End ();
Return true;
}
Catch (exception ex)
{
Ex. Message. tostring ();
Return false;
}
}

/// <Summary>
/// Delete special symbol
/// </Summary>
/// <Param name = "str"> </param>
/// <Returns> </returns>
Public String delquota (string Str)
{
String result = STR;
String [] strquota = {"~ ","! "," @ "," # "," $ "," % "," ^ ","&","*","(",")", "'",";","'",",",". ","/",": ","/, "," <","> ","? "};
For (INT I = 0; I <strquota. length; I ++)
{
If (result. indexof (strquota [I])>-1)
Result = result. Replace (strquota [I], "");
}
Return result;
}

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.