简体   繁体   中英

How to get Header text as required in CSV file in Windows Application?

I am using the following code to generate CSV file:

private void button1_Click(object sender, EventArgs e)
    {

        Stopwatch swra = new Stopwatch();
        swra.Start();
        string NewconnectionString = connectionString;
        StreamWriter CsvfileWriter = new StreamWriter(@"D:\testfile.csv");
        string sqlselectQuery = "select * from tblProperty";
        SqlCommand sqlcmd = new SqlCommand();

        SqlConnection spContentConn = new SqlConnection(NewconnectionString);
        sqlcmd.Connection = spContentConn;
        sqlcmd.CommandTimeout = 0;
        sqlcmd.CommandType = CommandType.Text;
        sqlcmd.CommandText = sqlselectQuery;
        spContentConn.Open();
        using (spContentConn)
        {
            using (SqlDataReader sdr = sqlcmd.ExecuteReader())
            using (CsvfileWriter)
            {
                string columnNames = Enumerable.Range(0, sdr.FieldCount).Select(i => sdr.GetName(i)).ToString();


                CsvfileWriter.WriteLine(string.Join(",", columnNames));
                while (sdr.Read())
                    //based on your Table columns you can increase and decrese columns
                    CsvfileWriter.WriteLine(sdr[0].ToString() + "," + sdr[1].ToString() + "," + sdr[2].ToString() + "," + sdr[3].ToString() + "," + sdr[4].ToString() + "," + sdr[5].ToString() + "," + sdr[6].ToString() + "," + sdr[7].ToString() + "," + sdr[8].ToString() + "," + sdr[9].ToString() + ",");

            }
        }
        swra.Stop();
        Console.WriteLine(swra.ElapsedMilliseconds);
    }

And in out put i get the data as below screen shot 这个 please help me. Thanks in advance.

 IEnumerable<string> columnNames = Enumerable.Range(0, sdr.FieldCount)
                                             .Select(i => sdr.GetName(i));

 CsvfileWriter.WriteLine(string.Join(",", columnNames.ToArray()));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM