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;
}