C # Datatable export CSV algorithm, c # datatable export csv
/// <Summary>
/// Export data to a CSV file
/// </Summary>
/// <Param name = "dtExportTable"> datatable to be exported </param>
/// <Param name = "dicColumnsInfo"> name of the exported column dictionary, key datable column, and value column to be exported </param>
/// <Param name = "FilePath"> exported file path </param>
Public static void ExportCSV (DataTable dtExportTable, Dictionary <string, string> dicColumnsInfo, string FilePath)
{
List <string> notExist = new List <string> ();
If (dtExportTable! = Null & dicColumnsInfo! = Null)
{
Foreach (string key in dicColumnsInfo. Keys)
{
If (! DtExportTable. Columns. Contains (key ))
{
NotExist. Add (key );
}
}
}
Foreach (string key in notExist)
{
DicColumnsInfo. Remove (key );
}
For (int I = dtExportTable. Columns. Count-1; I> = 0; I --)
{
String colName = dtExportTable. Columns [I]. ColumnName;
If (! DicColumnsInfo. ContainsKey (colName ))
{
DtExportTable. Columns. RemoveAt (I );
}
}
If (dtExportTable = null | dtExportTable. columns. count <= 0 | dtExportTable. rows. count <= 0 | dicColumnsInfo = null | dicColumnsInfo. count <= 0 | string. isNullOrEmpty (FilePath ))
Throw new Exception ("the export condition does not meet! ");
StringBuilder sbResult = new StringBuilder ();
Int ColCount = dtExportTable. Columns. Count;
String Header = string. Empty;
For (int I = 0; I <ColCount; I ++)
{
If (String. IsNullOrEmpty (Header ))
{
Header = dicColumnsInfo [dtExportTable. Columns [I]. ColumnName];
}
Else
{
Header + = "," + dicColumnsInfo [dtExportTable. Columns [I]. ColumnName];
}
}
SbResult. AppendLine (Header); // Add a Header
Foreach (DataRow dr in dtExportTable. Rows)
{
String rowstring = string. Empty;
For (int I = 0; I <ColCount; I ++)
{
If (String. IsNullOrEmpty (rowstring ))
{
Rowstring = dr [I]. ToString ();
}
Else
{
Rowstring + = "," + dr [I]. ToString ();
}
}
SbResult. AppendLine (rowstring); // Add a row
}
File. WriteAllText (FilePath, sbResult. ToString ());
}