Export Dataset/Datatable to CSV File Using C# and VB.NET

watch_later Monday, December 3, 2018
comment 2 Comments

Introduction


In this article i will show you how to write csv file using dataset/datatable in C# and VB.NET and also explain how you can export dataset/datatble in csv file in c# and vb.net.

while you working with csv and try to write csv files suppose if you have data with comma(,) and double quote("") then may you can't write csv as per your requirement and may your csv will not be generate properly as per your requirement.
Export Dataset/Datatable to CSV File Using C# and VB.NET
Export Dataset/Datatable to CSV File Using C# and VB.NET

There possibility if you working with big data applications and you have lot's of data and clients give you a requirement like they wants to export that all the data in excel but due to too larger data and you may get exception like out of memory exception error, So there is best option is you can write csv file and fixed this issue because csv file able to accept this kind of requirement.

Today i faced same issue in my office actually our client said they need all the data of whole year 2017-2018 with every transaction and its history also,  and i have created stored procedure and return datatable now i have datatable and i directly export that in .xls file and i got error like "Out of Memory Exception Error", and to fixed this issue i have search too many websites on internet but didn't get solution as per my expectation, then my TL said "Nikunj you can try and export that all the data In .CSV file that may helps you" and now i have created one custom method and implemented in my c# code and really that helps me i got a solution as per my requirement.

Now, to overcome this kind of issue here i will show you a custom method that i have created "WriteCSV" in the below article with example.

Requirement


1) Create DataSet/Datatable
2) Write a Custom Method/Function for Write .CSV file
3) Export Dataset/Datatable to .CSV File.

Implementation


First, to write csv file we need a dataset/datatable and hear i creating datatable using c# for demonstration, you can get datatable using stored procedure also as per your need.

C#

DataTable GetData()
       {
           DataTable dt = new DataTable();
           dt.Columns.Add("CustomerId"typeof(int));
           dt.Columns.Add("CustomerName"typeof(string));
           dt.Columns.Add("ProductName"typeof(string));
           dt.Columns.Add("Price"typeof(double));
           dt.Rows.Add(1, "Nikunj Satasiya""Laptop", 37000);
           dt.Rows.Add(2, "Hiren Dobariya""Mouse", 820);
           dt.Rows.Add(3, "Vivek Ghadiya""Pen", 250);
           dt.Rows.Add(4, "Pratik Pansuriya""Laptop", 42000);
           dt.Rows.Add(5, "Sneha Patel""Lip Bam", 130);
           dt.Rows.Add(6, "Jhon Smith""Sigar", 150);
           return dt;
       }

VB

Private Function GetData() As DataTable
        Dim dt As DataTable = New DataTable
        dt.Columns.Add("CustomerId"GetType(System.Int32))
        dt.Columns.Add("CustomerName"GetType(System.String))
        dt.Columns.Add("ProductName"GetType(System.String))
        dt.Columns.Add("Price"GetType(System.Double))
        dt.Rows.Add(1, "Nikunj Satasiya""Laptop", 37000)
        dt.Rows.Add(2, "Hiren Dobariya""Mouse", 820)
        dt.Rows.Add(3, "Vivek Ghadiya""Pen", 250)
        dt.Rows.Add(4, "Pratik Pansuriya""Laptop", 42000)
        dt.Rows.Add(5, "Sneha Patel""Lip Bam", 130)
        dt.Rows.Add(6, "Jhon Smith""Sigar", 150)
        Return dt
    End Function
Datatable
Datatable

Now We will write a custom function/method to write csv file. 

C#

public static string WriteCSV(string input)
        {
            try
            {
                if (input == null)
                    return string.Empty;
 
                bool containsQuote = false;
                bool containsComma = false;
                int len = input.Length;
                for (int i = 0; i < len && (containsComma == false || containsQuote == false); i++)
                {
                    char ch = input[i];
                    if (ch == '"')
                        containsQuote = true;
                    else if (ch == ',')
                        containsComma = true;
                }
 
                if (containsQuote && containsComma)
                    input = input.Replace("\"""\"\"");
 
                if (containsComma)
                    return "\"" + input + "\"";
                else
                    return input;
            }
            catch
            {
                throw;
            }
        }

VB

Public Shared Function WriteCSV(ByVal input As StringAs String
        Try
            If (input Is NothingThen
                Return String.Empty
            End If
 
            Dim containsQuote As Boolean = False
            Dim containsComma As Boolean = False
            Dim len As Integer = input.Length
            Dim i As Integer = 0
            Do While ((i < len) _
                        AndAlso ((containsComma = False) _
                        OrElse (containsQuote = False)))
                Dim ch As Char = input(i)
                If (ch = Microsoft.VisualBasic.ChrW(34)) Then
                    containsQuote = True
                ElseIf (ch = Microsoft.VisualBasic.ChrW(44)) Then
                    containsComma = True
                End If
 
                i = (i + 1)
            Loop
 
            If (containsQuote AndAlso containsComma) Then
                input = input.Replace(""""", """""")"if, (containsCommaUnknown, """"" + input + """)
            Else
                Return input
            End If
 
        Catch  As System.Exception
            Throw
        End Try
 
    End Function
Now In click of button write following code

C#

private void btnCSV_Click(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            DataTable dt = GetData();
            foreach (DataRow dr in dt.Rows)
            {
                foreach (DataColumn dc in dt.Columns)
                    sb.Append(WriteCSV(dr[dc.ColumnName].ToString()) + ",");
                sb.Remove(sb.Length - 1, 1);
                sb.AppendLine();
            }
            File.WriteAllText(@"C:\Users\Nikunj-PC\Desktop\Demo\CodingvilaCSV.csv", sb.ToString());
            lblMsg.Text = "Successful";
        }

VB

Private Sub btnCSV_Click(ByVal sender As ObjectByVal e As EventArgs)
        Dim sb As StringBuilder = New StringBuilder
        Dim dt As DataTable = GetData
        For Each dr As DataRow In dt.Rows
            For Each dc As DataColumn In dt.Columns
                sb.Append((WriteCSV(dr(dc.ColumnName).ToString) + ","))
            Next
            sb.Remove((sb.Length - 1), 1)
            sb.AppendLine()
        Next
        File.WriteAllText("C:\Users\Nikunj-PC\Desktop\Demo\CodingvilaCSV.csv", sb.ToString)
        lblMsg.Text = "Successful"
    End Sub
Visualizer
Visualizer

If you analyzed the above code then hear I have one CSV file in my desktop location and I want to write that CSV file so I give fixed file path. you can use file open dialog also as per your need as well as also can change the path if you have filed file location.

OutPut

CSV File
CSV File

Summary


This article explains how you can export dataset/datatable to a csv file and also explains how to write a csv file using c# and vb.net.

Codingvila provides articles and blogs on web and software development for beginners as well as free Academic projects for final year students in Asp.Net, MVC, C#, Vb.Net, SQL Server, Angular Js, Android, PHP, Java, Python, Desktop Software Application and etc.

avatar

Good example. Thank you! It helped me with a project I am working on. There were some errors with the VB code for the input function. I fixed them in the code below.

Public Shared Function WriteCSV(ByVal input As String) As String
Try
If (input Is Nothing) Then
Return String.Empty
End If
Dim containsQuote As Boolean = False
Dim containsComma As Boolean = False
Dim len As Integer = input.Length
Dim i As Integer = 0
Do While ((i < len) _
AndAlso ((containsComma = False) _
OrElse (containsQuote = False)))
Dim ch As Char = input(i)
If (ch = Microsoft.VisualBasic.ChrW(34)) Then
containsQuote = True
ElseIf (ch = Microsoft.VisualBasic.ChrW(44)) Then
containsComma = True
End If

i = (i + 1)
Loop
If (containsQuote AndAlso containsComma) Then
input = input.Replace("""", """""")
End If
If (containsComma) Then
Return """" & input & """"
Else
Return input
End If
Catch ex As Exception
Throw
End Try
End Function

delete April 15, 2019 at 12:41 PM
avatar

Thank you for your valuable feedback. I will review your code and update the code in the article that you have fixed.

delete April 16, 2019 at 5:16 AM



sentiment_satisfied Emoticon