C# DataTable to CSV: 3 Easy Methods with Examples

2025-09-19 08:28:19 zaki zou

C# DataTable to CSV - Step-by-Step Guide

Exporting DataTable to CSV in C# is a common requirement for developers who need to save, share, or analyze tabular data efficiently. The DataTable object in .NET provides a structured way to store rows and columns in memory, but often you need to convert this data into a CSV file for Excel, reporting tools, or other systems.

This tutorial explains three easy methods to export DataTable to CSV in C#, complete with step-by-step instructions and practical code examples. Whether you are working with small datasets or large, production-level tables, these approaches will help you perform DataTable to CSV conversion in C# quickly and reliably.

Table of Contents

Why Export DataTable to CSV in C#

Exporting a DataTable to CSV in C# offers several key advantages:

  • Universal Data Format – CSV is supported by Excel, Google Sheets, databases, and many applications.
  • Readable and Simple – Unlike JSON or XML, CSV is human-readable and easy to edit manually.
  • Seamless Integration – Many enterprise applications, CRMs, and reporting tools accept CSV files.
  • Fast Performance – CSV generation is lightweight and efficient.
  • Cross-Platform Compatibility – CSV files can be opened and processed on any system.

Method 1: Manual C# DataTable to CSV Conversion Using StringBuilder

Manually exporting a DataTable to CSV in C# using StringBuilder gives you full control over formatting and escaping rules, making it ideal for small to medium datasets.

Steps to Convert DataTable to CSV in C# Using StringBuilder

  • Create or fetch a DataTable from your source (database, API, or manually).
  • Initialize a StringBuilder to store CSV content.
  • Append column headers by looping through DataTable.Columns.
  • Loop through DataTable rows and append each cell’s value.
  • Escape special characters like commas, quotes, or newlines.
  • Write the final string to a CSV file using File.WriteAllText.

Example Code

using System;
using System.Data;
using System.IO;
using System.Text;

namespace DataTableToCSV
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // -------------------------------
            // Step 1: Create a DataTable
            // -------------------------------
            DataTable table = new DataTable("Employees");

            // Define columns: ID, Name, Department, Salary, JoinDate, Email
            table.Columns.Add("ID", typeof(int));
            table.Columns.Add("Name", typeof(string));
            table.Columns.Add("Department", typeof(string));
            table.Columns.Add("Salary", typeof(decimal));
            table.Columns.Add("JoinDate", typeof(DateTime));
            table.Columns.Add("Email", typeof(string));

            // Add sample rows with richer data
            table.Rows.Add(1, "Alice Johnson", "HR", 60000, new DateTime(2019, 3, 15), "alice.johnson@example.com");
            table.Rows.Add(2, "Bob Smith", "IT", 75000, new DateTime(2018, 7, 22), "bob.smith@example.com");
            table.Rows.Add(3, "Charlie Brown", "Finance", 82000, new DateTime(2020, 1, 10), "charlie.brown@example.com");
            table.Rows.Add(4, "Diana Prince", "Marketing", 67000, new DateTime(2021, 5, 5), "diana.prince@example.com");
            table.Rows.Add(5, "Ethan Hunt", "Operations", 90000, new DateTime(2017, 9, 30), "ethan.hunt@example.com");
            table.Rows.Add(6, "Fiona Gallagher", "IT", 72000, new DateTime(2019, 11, 12), "fiona.gallagher@example.com");

            // -------------------------------
            // Step 2: Export DataTable to CSV
            // -------------------------------
            string csvPath = "employees.csv";
            DataTableToCsv(table, csvPath);

            Console.WriteLine($"CSV file successfully created: {csvPath}");
        }

        /// <summary>
        /// Converts a DataTable to a CSV file.
        /// </summary>
        /// <param name="dt">The DataTable to export</param>
        /// <param name="filePath">The path where CSV file will be saved</param>
        public static void DataTableToCsv(DataTable dt, string filePath)
        {
            // Use StringBuilder to efficiently build CSV content
            StringBuilder sb = new StringBuilder();

            // -------------------------------
            // Step 1: Add column headers
            // -------------------------------
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                sb.Append(dt.Columns[i].ColumnName);
                if (i < dt.Columns.Count - 1) sb.Append(","); // Add comma except for last column
            }
            sb.AppendLine();

            // -------------------------------
            // Step 2: Add rows
            // -------------------------------
            foreach (DataRow row in dt.Rows)
            {
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    string value;

                    // Format DateTime columns as "yyyy-MM-dd"
                    if (dt.Columns[i].DataType == typeof(DateTime))
                    {
                        value = ((DateTime)row[i]).ToString("yyyy-MM-dd");
                    }
                    else
                    {
                        value = row[i].ToString();
                    }

                    // Escape special characters: commas, quotes, newlines
                    if (value.Contains(",") || value.Contains("\"") || value.Contains("\n"))
                    {
                        value = "\"" + value.Replace("\"", "\"\"") + "\"";
                    }

                    sb.Append(value);

                    if (i < dt.Columns.Count - 1) sb.Append(",");
                }
                sb.AppendLine();
            }

            // -------------------------------
            // Step 3: Write CSV file
            // -------------------------------
            File.WriteAllText(filePath, sb.ToString(), Encoding.UTF8);
        }
    }
}

Output CSV

CSV Output Generated from DataTable using C# and StringBulder

Method 2: Large C# DataTable to CSV Export Using StreamWriter

For large DataTables, using StringBuilder can be memory-intensive. StreamWriter allows you to write rows line by line, which is efficient for large datasets.

Steps for StreamWriter-Based C# DataTable CSV Export

  • Create or retrieve your DataTable with the necessary data.
  • Initialize a StreamWriter with the output CSV file path and desired encoding (like UTF-8).
  • Write the header row using DataTable column names.
  • Iterate through DataTable rows and write each line to the file.
  • Escape values containing special characters (commas, quotes, newlines) to maintain CSV integrity.
  • Close the StreamWriter to release system resources.

Example Code

using System;
using System.Data;
using System.IO;
using System.Text;

namespace DataTableToCSV
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // -------------------------------
            // Step 1: Create a new DataTable for this example
            // -------------------------------
            DataTable table = new DataTable("Products");

            // Define columns: ProductID, ProductName, Category, Price, Stock, LaunchDate
            table.Columns.Add("ProductID", typeof(int));
            table.Columns.Add("ProductName", typeof(string));
            table.Columns.Add("Category", typeof(string));
            table.Columns.Add("Price", typeof(decimal));
            table.Columns.Add("Stock", typeof(int));
            table.Columns.Add("LaunchDate", typeof(DateTime));

            // Add sample rows with varied products
            table.Rows.Add(101, "Laptop Pro 15", "Electronics", 1500.99, 25, new DateTime(2023, 1, 10));
            table.Rows.Add(102, "Wireless Mouse", "Accessories", 29.95, 200, new DateTime(2022, 11, 5));
            table.Rows.Add(103, "Mechanical Keyboard", "Accessories", 79.99, 150, new DateTime(2022, 12, 1));
            table.Rows.Add(104, "4K Monitor", "Electronics", 399.50, 40, new DateTime(2023, 2, 20));
            table.Rows.Add(105, "USB-C Hub", "Accessories", 49.99, 300, new DateTime(2022, 9, 18));
            table.Rows.Add(106, "Gaming Chair", "Furniture", 259.99, 15, new DateTime(2023, 3, 5));

            // -------------------------------
            // Step 2: Export DataTable to CSV using StreamWriter
            // -------------------------------
            string csvPath = "products_stream.csv";
            DataTableToCsvStream(table, csvPath);

            Console.WriteLine($"CSV file successfully created: {csvPath}");
        }

        /// <summary>
        /// Export a DataTable to CSV using StreamWriter (efficient for large datasets)
        /// </summary>
        /// <param name="dt">The DataTable to export</param>
        /// <param name="filePath">The CSV file path to save</param>
        public static void DataTableToCsvStream(DataTable dt, string filePath)
        {
            // Use StreamWriter for memory-efficient writing (row by row)
            using (StreamWriter writer = new StreamWriter(filePath, false, Encoding.UTF8))
            {
                // -------------------------------
                // Step 1: Write column headers
                // -------------------------------
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    writer.Write(dt.Columns[i].ColumnName);
                    if (i < dt.Columns.Count - 1)
                        writer.Write(","); // Add comma except for last column
                }
                writer.WriteLine();

                // -------------------------------
                // Step 2: Write rows
                // -------------------------------
                foreach (DataRow row in dt.Rows)
                {
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        string value;

                        // Format DateTime as yyyy-MM-dd
                        if (dt.Columns[i].DataType == typeof(DateTime))
                        {
                            value = ((DateTime)row[i]).ToString("yyyy-MM-dd");
                        }
                        else
                        {
                            value = row[i].ToString();
                        }

                        // Escape special characters: commas, quotes, newlines
                        if (value.Contains(",") || value.Contains("\"") || value.Contains("\n"))
                        {
                            value = "\"" + value.Replace("\"", "\"\"") + "\"";
                        }

                        writer.Write(value);

                        if (i < dt.Columns.Count - 1)
                            writer.Write(",");
                    }
                    writer.WriteLine();
                }
                // StreamWriter is automatically closed at the end of the using block
            }
        }
    }
}

Output CSV

CSV Output Generated from DataTable using C# and StringWriter

Method 3: Use Spire.XLS for .NET to Convert DataTable to CSV in C#

For production-ready applications, libraries like Spire.XLS for .NET provide a reliable and efficient way to handle C# DataTable to CSV export. The library automatically handles special characters, delimiters, and encoding, reducing manual coding effort and ensuring consistent, accurate output.

Get Started with Spire.XLS for .NET

To use Spire.XLS in your C# project, install it via NuGet:

  • Open your project in Visual Studio.
  • Go to Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution…
  • Search for “Spire.XLS” and click Install.

Alternatively, you can install it quickly using the Package Manager Console:

Install-Package Spire.XLS

Once installed, you can effortlessly export DataTables to CSV and perform further operations on the resulting files, such as converting CSV to Excel or importing CSV back into a DataTable, all efficiently within your .NET applications.

Steps for Spire.XLS-Based C# Datatable to CSV Export

  • Prepare your DataTable with the data to export.
  • Create a Workbook object using Spire.XLS.
  • Insert the DataTable into a worksheet.
  • Save the worksheet as CSV, specifying delimiter and encoding.

Example Code

using Spire.Xls;
using System;
using System.Data;
using System.Text;

namespace DataTableToCSV
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // -------------------------------
            // Step 1: Create a new DataTable for books
            // -------------------------------
            DataTable dt = new DataTable("Books");

            // Define columns: BookID, Title, Author, Genre, Price, PublishDate
            dt.Columns.Add("BookID", typeof(int));
            dt.Columns.Add("Title", typeof(string));
            dt.Columns.Add("Author", typeof(string));
            dt.Columns.Add("Genre", typeof(string));
            dt.Columns.Add("Price", typeof(double));
            dt.Columns.Add("PublishDate", typeof(DateTime));

            // Add sample rows
            dt.Rows.Add(201, "The Great Gatsby", "F. Scott Fitzgerald", "Classic", 10.99, new DateTime(1925, 4, 10));
            dt.Rows.Add(202, "1984", "George Orwell", "Dystopian", 9.99, new DateTime(1949, 6, 8));
            dt.Rows.Add(203, "To Kill a Mockingbird", "Harper Lee", "Classic", 12.50, new DateTime(1960, 7, 11));
            dt.Rows.Add(204, "The Hobbit", "J.R.R. Tolkien", "Fantasy", 15.75, new DateTime(1937, 9, 21));
            dt.Rows.Add(205, "Clean Code", "Robert C. Martin", "Programming", 32.99, new DateTime(2008, 8, 1));
            dt.Rows.Add(206, "The Pragmatic Programmer", "Andrew Hunt", "Programming", 29.95, new DateTime(1999, 10, 20));

            // -------------------------------
            // Step 2: Create a Workbook and insert DataTable
            // -------------------------------
            Workbook workbook = new Workbook();
            Worksheet sheet = workbook.Worksheets[0];

            // Insert the DataTable into the worksheet starting from row 1, column 1
            // Include column headers
            sheet.InsertDataTable(dt, true, 1, 1);

            // -------------------------------
            // Step 3: Save the worksheet as CSV
            // -------------------------------
            // Parameters: file name, delimiter, encoding
            sheet.SaveToFile("books.csv", ",", Encoding.UTF8);

            // Release resources
            workbook.Dispose();
        }
    }
}

Output CSV

CSV Output Generated from DataTable using C# and Spire.XLS Library

Benefits of Using Spire.XLS

  • Automatic handling of special characters, delimiters, and encodings – no manual escaping needed.
  • Supports both CSV import and export, making it flexible for different workflows.
  • Simplifies production-level code – less boilerplate and fewer errors compared to manual methods.
  • Scalable for large datasets – works efficiently even with thousands of rows.

Performance Comparison of DataTable to CSV Methods

To better understand the strengths and trade-offs of each approach, here’s a side-by-side comparison of StringBuilder, StreamWriter, and Spire.XLS when exporting a DataTable to CSV.

Method Best For Performance Memory Usage Code Complexity Notes
StringBuilder Small datasets (<10k rows) Medium High Moderate Full control over output, but less efficient for large files
StreamWriter Large datasets (10k+ rows) High Low Moderate Writes row-by-row, prevents memory overload
Spire.XLS Production & enterprise High Optimized Low Handles escaping, encoding, and large datasets automatically

Which Method Should You Use?

While the comparison table highlights the technical differences, choosing the right method depends on your specific scenario, such as dataset size, performance requirements, and production needs.

  • Choose StringBuilder if you need complete control over CSV formatting and you’re working with small to medium datasets.
  • Choose StreamWriter if you’re exporting large datasets and want a memory-efficient solution.
  • Choose Spire.XLS if you need a production-ready, reliable, and low-maintenance approach, especially when handling special cases or integrating into enterprise workflows.

Handling Special Cases and Best Practices for DataTable to CSV

When exporting a DataTable to CSV in C#, it’s important to follow best practices and also be aware of some special cases that could affect your CSV output. Handling these properly ensures your files are clean, reliable, and easy to use.

  • Handling Special Cases
    • Null values – Replace DBNull with empty strings or placeholders so that missing data doesn’t break your CSV.
    • Custom delimiters – If your data contains commas, consider using ; or tabs (\t) to avoid confusion.
    • Special characters – Values with quotes, commas, or line breaks should be properly escaped to maintain CSV integrity.
    • Encoding considerations – UTF-8 is recommended for most scenarios, but some systems may require UTF-16 or ANSI.
    • Large datasets – For very large tables, consider splitting files or using memory-efficient methods like StreamWriter to avoid performance issues.
  • Best Practices
    • Stick with UTF-8 encoding for compatibility across platforms and tools.
    • Test with special cases such as nulls, commas, quotes, and multiline values to prevent unexpected errors.
    • Pick the right method – StringBuilder works fine for small tables, StreamWriter is better for large datasets, and Spire.XLS is ideal for production-ready solutions.
    • Document your CSV structure clearly so others know how to interpret the data.

Conclusion

Mastering C# DataTable to CSV is an essential skill for developers working with tabular data. This guide covered three practical approaches: using StringBuilder for small datasets, employing StreamWriter for efficient and memory-friendly handling of large tables, and leveraging the Spire.XLS library for a reliable, production-ready solution that automatically manages complex scenarios.

By following these step-by-step examples, you can perform C# DataTable to CSV conversion confidently, ensuring your data is accurate, shareable, and ready for integration or further analysis.

FAQs

Q1: How can I convert a DataTable to CSV in C# efficiently?

A1: You can use three methods: manual conversion with StringBuilder for small datasets, StreamWriter for large datasets, or the Spire.XLS library for a production-ready solution. Each method ensures proper handling of commas, quotes, and newlines.

Q2: What is the best way to export large C# DataTables to CSV?

A2: For large datasets, StreamWriter is recommended because it writes rows line by line, reducing memory usage. Spire.XLS is another reliable option for production environments.

Q3: How do I handle special characters and null values when exporting DataTable to CSV in C#?

A3: Always escape commas, quotes, and line breaks. Replace null or DBNull values with empty strings or placeholders. Using Spire.XLS automatically handles most of these cases.

Q4: Can I customize delimiters and encoding when exporting a DataTable to CSV?

A4: Yes, you can specify delimiters like ,, ;, or \t and choose encoding such as UTF-8, UTF-16, or ANSI depending on system requirements.

Q5: Why should I use Spire.XLS instead of manual or StreamWriter methods?

A5: Spire.XLS simplifies CSV export by handling escaping, delimiters, and encoding automatically, reduces code complexity, and is ideal for medium to large datasets or production-level applications.

Q6: How do I ensure my exported CSV is compatible with Excel and other applications?

A6: Use UTF-8 encoding, escape special characters, and consistently format headers. Testing the output in Excel or other target applications helps avoid compatibility issues.

See Also