Datatable is used in. Net projects to cache data. datatable indicates a table with data in memory. CSV files were first used in a simple database. Because of their simple format and strong openness, they were first marked by their own gallery by the scanner. A csv file is a plain text file. Each line represents many attributes of an image.
Using C # In the. Net project to convert a able to a CSV file provides a common method. The Code is as follows:
/// <Summary> /// convert the datatable to a CSV file // </Summary> /// <Param name = "DT"> datatable </param> // /<Param name = "filepath"> file path </param> Public static void savecsv (datatable DT, string filepath) {filestream FS = NULL; streamwriter Sw = NULL; try {FS = new filestream (filepath + dt. tablename + ". CSV ", filemode. create, fileaccess. write); Sw = new streamwriter (FS, encoding. default); var DATA = string. empty; // Write the column name for (VAR I = 0; I <DT. columns. count; I ++) {Data + = DT. columns [I]. columnname; if (I <DT. columns. count-1) {Data + = "," ;}} SW. writeline (data); // write each row of data for (VAR I = 0; I <DT. rows. count; I ++) {DATA = string. empty; For (var j = 0; j <DT. columns. count; j ++) {Data + = DT. rows [I] [J]. tostring (); If (j <DT. columns. count-1) {Data + = "," ;}} SW. writeline (data) ;}} catch (ioexception Ex) {Throw new ioexception (ex. Message, ex) ;}finally {If (SW! = NULL) SW. Close (); If (FS! = NULL) fs. Close ();}}
Convert a able to a CSV file