Converts a able to a CSV file, and a DataTable to a csv file.
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 ();}}