Export to CSV in Windows using C#

harish

New Member
I want to use the export a large number of records report to CSV, as i had tried it to export in excel it is taking time and some times its not completing the process and giving some error, so someone suggest me export data in CSV file, i have tried the following code from Export to CSV\[code\]private void button1_Click(object sender, EventArgs e) { Stopwatch swra = new Stopwatch(); swra.Start(); string NewconnectionString = "myCoonectionString"; StreamWriter CsvfileWriter = new StreamWriter(@"D:\testfile.csv"); string sqlselectQuery = "select * from Mytable"; 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) { //This Block of code for getting the Table Headers DataTable Tablecolumns = new DataTable(); for (int i = 0; i < sdr.FieldCount; i++) { Tablecolumns.Columns.Add(sdr.GetName(i)); } CsvfileWriter.WriteLine(string.Join(",", Tablecolumns.Columns.Cast<datacolumn>().Select(csvfile => csvfile.ColumnName))); //This block of code for getting the Table Headers while (sdr.Read()) //based on your Table columns you can increase and decrese columns YourWriter.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() + "," + sdr[10].ToString() + "," + sdr[11].ToString() + ","); } } swra.Stop();\[/code\]Console.WriteLine(swra.ElapsedMilliseconds);}I am getting Error on CsvfileWriter.WriteLine(string.Join(",", Tablecolumns.Columns.Cast().Select(csvfile => csvfile.ColumnName)));That is for datacolumn, i dont know how to resolve it please help.EDITI am getting compile Error:\[code\]Error 1 The type or namespace name 'datacolumn' could not be found (are you missing a using directive or an assembly reference?\[/code\]When i tried to replace it with DataColumn then i got some other error is below:\[code\]Error 1 Instance argument: cannot convert from 'System.Data.DataColumnCollection' to 'System.Data.EnumerableRowCollectio' \[/code\]and\[code\]Error 2 'System.Data.DataColumnCollection' does not contain a definition for 'Cast' and the best extension method overload 'System.Data.EnumerableRowCollectionExtensions.Cast<TResult>(System.Data.EnumerableRowCollection)' has some invalid arguments\[/code\]
 
Back
Top