Convert CSV to Datatable in C#, VB.NET

CSV to datatable is a data issue that is most concerned by programmer and developers. Compared with Excel, CSV is a simple file format. Is CSV to datatable more easier than Excel to datatable? Please try the following solution. This section will introduce a solution to quickly convert CSV to datatable with C#, VB.NET via a .NET Excel component.

Spire.XLS for .NET, featured as fast and easy, enables you to convert CSV to datatable via two main methods:

  • Workbook.LoadFromFile(string fileName, string separator). This method can be used to load a CSV file.
  • Worksheet.ExportDataTable(). This method is a core method that can be called to export CSV to datatable.

Before viewing the whole code, feel free to download Spire.XLS for .NET and preview below picture.

CSV to Datatable

Detail Code:

using Spire.Xls;
using Spire.Xls.Converter;

namespace ExportDataFromCSV
    public partial class Form1 : Form
        public Form1()

        private void button1_Click(object sender, EventArgs e)
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = "CSV document(*.csv)|*.csv";
            DialogResult result = dialog.ShowDialog();
            if (result == DialogResult.OK)
                string csvFile = dialog.FileName;
                Workbook workbook = new Workbook();
                workbook.LoadFromFile(@"..\csvtodatatable.csv", ",");
                Worksheet worksheet = workbook.Worksheets[0];
                System.Data.DataTable t = worksheet.ExportDataTable();
                this.dataGridView1.DataSource = t;             
Imports Spire.Xls
Imports Spire.Xls.Converter

Namespace ExportDataFromCSV
    Public Class Form1
        Inherits Form
        Public Sub New()
        End Sub
        Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs)
            Dim dialog As OpenFileDialog = New OpenFileDialog
            dialog.Filter = "CSV document(*.csv)|*.csv"
            Dim result As DialogResult = dialog.ShowDialog
            If (result = DialogResult.OK) Then
                Dim csvFile As String = dialog.FileName
                Dim workbook As Workbook = New Workbook
                workbook.LoadFromFile("..\csvtodatatable.csv", ",")
                Dim worksheet As Worksheet = workbook.Worksheets(0)
                Dim t As System.Data.DataTable = worksheet.ExportDataTable
                Me.dataGridView1.DataSource = t
            End If
        End Sub
    End Class
End Namespace

Spire.XLS is a .NET Excel component, which enables users to perform a wide range of Excel document processing tasks directly, such as generate, read, write and modify Excel document in WPF, .NET and Silverlight.