How to Export DataTable to CSV through DataGridView?

When we export data out from Database we may have requirements of exporting data from Datatable to CSV because CSV is a simple file format that is widely supported. CSV (The comma-separated values) file format is a set of file formats used to store tabular data in which numbers and text are stored in plain textual form that can be read in a text editor. Lines in the text file represent rows of a table, and commas in a line separate what are fields in the table row.

Here we mainly discuss how to Export Datatable to CSV with Spire.DataExport for .NET.

Download Spire.DataExport (or Spire.Office) with .NET Framework together. Only 2 Simple steps you can finish the whole datatable to CSV exporting process.

Step 1: Load Data Information

Before exporting data from DataTable, we should load data information from data source. And select which information we need export. Through DataGridVew, we even can preview and modify data information. So, in this step, our job is to prepare data which is about to be exported out.

[C#]
	
private void btnLoad_Click(object sender, EventArgs e)
{
  using (OleDbConnection oleDbConnection = new OleDbConnection())
  {
    oleDbConnection.ConnectionString = this.textBox1.Text;
    OleDbCommand oleDbCommand = new OleDbCommand();
    oleDbCommand.CommandText = this.textBox2.Text;
    oleDbCommand.Connection = oleDbConnection;
    using (OleDbDataAdapter da = new OleDbDataAdapter(oleDbCommand))
      {
      DataTable dt = new DataTable();
      da.Fill(dt);
       dataGridView1.DataSource = dt;
      }
  }
}

Effect Screenshot

Datatable to CSV

Step 2: Set Export into CSV

Spire.DataExport allows user to export data into most popular file formats including MS Excel, MS Word, HTML, PDF, XML, CSV, DBF, DIF, etc. Here we need set it as CSV format. Spire.DataExport will create a new CSV file and through DataGridView export data into CSV file. You also can rename the file as you like.

[C#]
private void btnRUN_Click(object sender, EventArgs e)
{
  TXTExport CSVExport = new TXTExport();
  CSVExport.DataSource = Spire.DataExport.Common.ExportSource.DataTable;
  CSVExport.DataTable = this.dataGridView1.DataSource as DataTable;
  CSVExport.ActionAfterExport = Spire.DataExport.Common.ActionType.OpenView;
  CSVExport.FileName = "CSV0721.csv";
  CSVExport.SaveToFile();
}

Effect Screenshot

Datatable to CSV