c# program to export data to .csv on specfic column only

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • doubtful1
    New Member
    • Jun 2015
    • 2

    c# program to export data to .csv on specfic column only

    Hi,
    i have program that retrieves data from database and writes to a .csv using c#.The test.csv has 7 columns.How to export data to specific ordinal columns only .I need to update only colums2,3,5and 6.


    here's snippet code:


    Code:
                using (SqlConnection con1 = new SqlConnection(ConnectionString))
                {
                    con1.Open();
                    SqlDataAdapter da =
                        new SqlDataAdapter(
                            "select Name,Speed,Month,ModelNo,Number from Test_MT " , con1);
    
                    
    
                    DataTable dt = new DataTable();
                    da.Fill(dt);
    
    
    
    
    
                    if (dt.Columns.Count != 0)
                    {
                        for (int i = 0; i < dt.Columns.Count; i++)
                        {
                            sb.Append((string) dt.Columns[2].ColumnName);
                            sb.Append(i == dt.Columns.Count - 1 ? "\n" : ",");
                        }
                        foreach (DataRow row in dt.Rows)
                        {
                            for (int i = 0; i < dt.Columns.Count; i++)
                            {
                                sb.Append(row[i].ToString().Replace("\r\n", "").Replace(",", ""));
                                sb.Append(i == dt.Columns.Count - 1 ? "\n" : ",");
                            }
    
                        }
                    }
                
                
                     
    
                    File.WriteAllText(@fileLocation, sb.ToString(), Encoding.UTF8);
    Last edited by Rabbit; Jun 2 '15, 04:16 PM. Reason: Please use [code] and [/code] tags when posting code or formatted data.
  • Rabbit
    Recognized Expert MVP
    • Jan 2007
    • 12517

    #2
    Please use code tags when posting code or formatted data.

    Your thread has been moved to the C# forum.

    I'm not really sure what you're asking.

    If you want to export only certain columns, then only select those columns in your select query.

    If you want to export create blank columns in the csv, then either replicate the blank columns in your select query, or append the blank columns in your string that you write to the csv.

    Comment

    Working...