CsvHelper icon indicating copy to clipboard operation
CsvHelper copied to clipboard

export datatable to csv

Open Wagimo opened this issue 5 years ago • 6 comments

Existe la implementación que exporte el contenido de un DataTable a un archivo .csv?

Wagimo avatar Oct 23 '19 20:10 Wagimo

https://joshclose.github.io/CsvHelper/examples/data-table/

JoshClose avatar Oct 25 '19 15:10 JoshClose

Hi @JoshClose I think Wagimo was looking for a way to write DataTables to CSV files. At the link you provided, I only see information about how to read a CSV file to a DataTable, but not the reverse. Am I missing something?

johnyesberg avatar Mar 22 '20 04:03 johnyesberg

@johnyesberg Oops, thanks. I'll need to add this to the documentation.

You could go through the rows and columns like this.

void Main()
{
	var dt = new DataTable();
	dt.Columns.Add("Id", typeof(int));
	dt.Columns.Add("Name", typeof(string));
	
	var row = dt.NewRow();
	row["Id"] = 1;
	row["Name"] = "one";
	dt.Rows.Add(row);

	row = dt.NewRow();
	row["Id"] = 2;
	row["Name"] = "two";
	dt.Rows.Add(row);
	
	using (var writer = new StringWriter())
	using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
	{		
		foreach (DataColumn dc in dt.Columns)
		{			
			csv.WriteField(dc.ColumnName);
		}
		csv.NextRecord();
		
		foreach (DataRow dr in dt.Rows)
		{			
			foreach (DataColumn dc in dt.Columns)
			{
				csv.WriteField(dr[dc]);
			}
			csv.NextRecord();
		}

		writer.ToString().Dump();
	}
}

Or you could use a DataReader and to it like this.

void Main()
{
	var dt = new DataTable();
	dt.Columns.Add("Id", typeof(int));
	dt.Columns.Add("Name", typeof(string));
	
	var row = dt.NewRow();
	row["Id"] = 1;
	row["Name"] = "one";
	dt.Rows.Add(row);

	row = dt.NewRow();
	row["Id"] = 2;
	row["Name"] = "two";
	dt.Rows.Add(row);
	
	using (var writer = new StringWriter())
	using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
	{
		using (var reader = dt.CreateDataReader())
		{
			for (var i = 0; i < reader.FieldCount; i++)
			{
				csv.WriteField(reader.GetName(i));
			}
			csv.NextRecord();
			
			while (reader.Read())
			{
				csv.WriteField(reader.GetFieldValue<int>("Id"));
				csv.WriteField(reader.GetFieldValue<string>("Name"));
				csv.NextRecord();
			}
		}

		writer.ToString().Dump();
	}
}

If there are better ways, let me know. I'm not too familiar with data tables.

JoshClose avatar Mar 23 '20 17:03 JoshClose

I suggest this method add to library, because it's really useful.

dameng324 avatar Jan 25 '21 16:01 dameng324

Agreed, it would be nice to be included by default.

You can create an extension method yourself for now:

 public static class MyCsvWriterExtension
 {
     public static void ExportDataTable(this CsvWriter writer, DataTable dt)
     {
         // Write the header
         foreach (DataColumn column in dt.Columns)
         {
             writer.WriteField(column.ColumnName);
         }
         writer.NextRecord();

         // Write the rows
         foreach (DataRow row in dt.Rows)
         {
             foreach (DataColumn column in dt.Columns)
             {
                 writer.WriteField(row[column]);
             }
             writer.NextRecord();
         }
     }
 }

ChibiPhoenixGithub avatar Jan 31 '22 11:01 ChibiPhoenixGithub