DI
ditchnedjib
Blocked user by Spotware at 20 Feb 2023, 10:37
0 follower(s) 0 following 1 subscription(s)

Information

Username: ditchnedjib
Member since: 21 Jul 2022
Last login: 21 Jul 2022
Status: Blocked

Activity

Where Created Comments
Algorithms 0 1
Forum Topics 0 0
Jobs 0 0

Last Algorithm Comments

DI
ditchnedjib · 1 year ago

public static class OperationsUtlity  
     {  
        public static DataTable createDataTable()  
        {  
            DataTable table = new DataTable();     
                //columns  
            table.Columns.Add("ID", typeof(int));     
            table.Columns.Add("NAME", typeof(string));     
            table.Columns.Add("CITY", typeof(string));    
  
                //data  
            table.Rows.Add(111, "Devesh", "Ghaziabad");     
            table.Rows.Add(222, "ROLI", "KANPUR");     
            table.Rows.Add(102, "ROLI", "MAINPURI");     
            table.Rows.Add(212, "DEVESH", "KANPUR");  
            table.Rows.Add(102, "NIKHIL", "GZB");  
            table.Rows.Add(212, "HIMANSHU", "NOIDa");  
            table.Rows.Add(102, "AVINASH", "NOIDa");  
            table.Rows.Add(212, "BHUPPI", "GZB");  
              
             return table;  
          }  
         
    } 
 

 

Create a static class

public static class  CSVUtlity  { }
Add Extention Method 

public static void ToCSV(this DataTable dtDataTable, string strFilePath){ 
public static void ToCSV(this DataTable dtDataTable, string strFilePath) {  
    StreamWriter sw = new StreamWriter(strFilePath, false);  
    //headers    
    for (int i = 0; i < dtDataTable.Columns.Count; i++) {  
        sw.Write(dtDataTable.Columns[i]);  
        if (i < dtDataTable.Columns.Count - 1) {  
            sw.Write(",");  
        }  
    }  
Apkbeer.com

Convert To csv

    sw.Write(sw.NewLine);  
    foreach(DataRow dr in dtDataTable.Rows) {  
        for (int i = 0; i < dtDataTable.Columns.Count; i++) {  
            if (!Convert.IsDBNull(dr[i])) {  
                string value = dr[i].ToString();  
                if (value.Contains(',')) {  
                    value = String.Format("\"{0}\"", value);  
                    sw.Write(value);  
                } else {  
                    sw.Write(dr[i].ToString());  
                }  
            }  
            if (i < dtDataTable.Columns.Count - 1) {  
                sw.Write(",");  
            }  
        }  
        sw.Write(sw.NewLine);  
    }  
    sw.Close();