How to Export Dataset to Excel in C

Cody Schneider8 min read

Generating an Excel report from your C# application is a common request, and for good reason - it's the go-to tool for business users who need to slice, dice, and visualize data. This guide walks you through the most practical methods for exporting your datasets into Excel-friendly formats using C#, covering everything from simple CSV dumps to creating professionally formatted XLSX files with powerful libraries.

GraphedGraphed

Still Building Reports Manually?

Watch how growth teams are getting answers in seconds — not days.

Watch Graphed demo video

Why Export Data to Excel from Your C# App?

While developers might live in IDEs and databases, most of your colleagues in marketing, sales, and finance live in spreadsheets. Exporting data to Excel serves a critical business need by empowering non-technical team members. When you provide data in a .xlsx or .csv file, you’re giving them the freedom to:

  • Analyze Data Freely: They can sort, filter, and pivot data without needing a developer to write a new query.
  • Create Visualizations: Users can build their own charts and graphs to identify trends and present findings.
  • Share Insights: Excel files are easily shared and understood across different departments and even with outside partners.
  • Perform Ad-Hoc Reporting: It answers the question, "Can you just pull this data for me?" and allows them to answer follow-up questions on their own.

In short, it bridges the gap between your application's raw data and actionable business intelligence for the rest of your team.

The Simplest Approach: Exporting to a CSV File

The Comma-Separated Values (CSV) format is the quickest and most straightforward way to export data. A CSV is a plain text file where values are separated by commas, making it universally compatible with Excel and nearly every other data analysis tool.

When to Use CSVs

CSVs are perfect for simple data dumps where formatting is not important. Choose this method if:

  • You need a quick and dirty export for raw analysis.
  • The primary goal is to import the data into another system.
  • You want to avoid adding external library dependencies to your project.

However, be aware of the limitations. CSV files don't support any formatting (like colors, bold fonts, or cell widths), data types (all data is treated as text), or formulas.

GraphedGraphed

Still Building Reports Manually?

Watch how growth teams are getting answers in seconds — not days.

Watch Graphed demo video

Step-by-Step Code Example

Let's say you have a simple list of Product objects that you want to export. No external libraries are needed, just standard C# and System.IO.

using System.Collections.Generic,
using System.IO,
using System.Text,

public class Product
{
    public int Id { get, set, }
    public string Name { get, set, }
    public decimal Price { get, set, }
    public int UnitsInStock { get, set, }
}

public class CsvExporter
{
    public void ExportProducts(List<Product> products, string filePath)
    {
        var sb = new StringBuilder(),

        // Add the header row
        sb.AppendLine("ID,Name,Price,Stock"),

        // Add the data rows
        foreach (var product in products)
        {
            // Handle commas in data by wrapping the text in quotes
            string name = product.Name.Contains(",") ? $"\"{product.Name}\"" : product.Name,
            sb.AppendLine($"{product.Id},{name},{product.Price},{product.UnitsInStock}"),
        }

        // Write the StringBuilder content to the file
        File.WriteAllText(filePath, sb.ToString()),
    }

    public static void Main(string[] args)
    {
        // 1. Create some sample data
        var productList = new List<Product>
        {
            new Product { Id = 101, Name = "Super Gizmo, Blue", Price = 19.99m, UnitsInStock = 50 },
            new Product { Id = 102, Name = "Basic Widget", Price = 5.49m, UnitsInStock = 200 },
            new Product { Id = 103, Name = "Ultimate Thingamajig", Price = 99.00m, UnitsInStock = 12 }
        },

        // 2. Define the file path
        string path = @"C:\Exports\products.csv",

        // 3. Export the data
        var exporter = new CsvExporter(),
        exporter.ExportProducts(productList, path),

        System.Console.WriteLine($"Export complete! File saved at {path}"),
    }
}

When you open products.csv in Excel, it will be neatly organized into columns. Notice how we wrapped the product name in double quotes to ensure the comma in "Super Gizmo, Blue" didn't break the column structure.

The Modern & Recommended Method: NuGet Libraries

When you need more than a simple data dump, it's time to create a "true" Excel file (.xlsx). Trying to do this from scratch is incredibly complex. Luckily, there are excellent third-party NuGet libraries that handle all the heavy lifting for you. This is the recommended approach for professional reporting.

Our library of choice for this tutorial is ClosedXML. It's a free, open-source library that is a wrapper around the Open XML SDK from Microsoft. It’s powerful, server-friendly, and has a very intuitive API.

Getting Started with ClosedXML

First, add the ClosedXML package to your C# project using the NuGet Package Manager:

Install-Package ClosedXML
GraphedGraphed

Still Building Reports Manually?

Watch how growth teams are getting answers in seconds — not days.

Watch Graphed demo video

Code Example: Creating a Formatted Excel Report

Using the same Product list, let's create a nicely formatted .xlsx file. With ClosedXML, you can easily add headers, style cells, set column widths, and ensure data types are correct.

using System.Collections.Generic,
using ClosedXML.Excel, // Add this using directive

public class Product
{
    public int Id { get, set, }
    public string Name { get, set, }
    public decimal Price { get, set, }
    public int UnitsInStock { get, set, }
}

public class ExcelExporter
{
    public void ExportProducts(List<Product> products, string filePath)
    {
        using (var workbook = new XLWorkbook())
        {
            var worksheet = workbook.Worksheets.Add("Products"),

            // --- Add Header ---
            var currentRow = 1,
            worksheet.Cell(currentRow, 1).Value = "ID",
            worksheet.Cell(currentRow, 2).Value = "Name",
            worksheet.Cell(currentRow, 3).Value = "Price",
            worksheet.Cell(currentRow, 4).Value = "Stock",

            // --- Style the Header ---
            var headerRange = worksheet.Range("A1:D1"),
            headerRange.Style.Font.Bold = true,
            headerRange.Style.Fill.BackgroundColor = XLColor.LightGray,
            headerRange.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center,

            // --- Add Data ---
            // Alternatively, you can insert the entire list at once!
            // worksheet.Cell("A2").InsertTable(products),

            foreach (var product in products)
            {
                currentRow++,
                worksheet.Cell(currentRow, 1).Value = product.Id,
                worksheet.Cell(currentRow, 2).Value = product.Name,

                // Set specific data types for better Excel functionality
                worksheet.Cell(currentRow, 3).Value = product.Price,
                worksheet.Cell(currentRow, 3).Style.NumberFormat.Format = "\"$\"#,##0.00", // Currency format

                worksheet.Cell(currentRow, 4).Value = product.UnitsInStock,
            }

            // --- Adjust Column Width to Content ---
            worksheet.Columns().AdjustToContents(),

            // --- Save the File ---
            workbook.SaveAs(filePath),
        }
    }

    public static void Main(string[] args)
    {
        // 1. Create some sample data
        var productList = new List<Product>
        {
            new Product { Id = 101, Name = "Super Gizmo, Blue", Price = 19.99m, UnitsInStock = 50 },
            new Product { Id = 102, Name = "Basic Widget", Price = 5.49m, UnitsInStock = 200 },
            new Product { Id = 103, Name = "Ultimate Thingamajig", Price = 99.00m, UnitsInStock = 12 }
        },

        // 2. Define the file path
        string path = @"C:\Exports\products_report.xlsx",

        // 3. Export the data
        var exporter = new ExcelExporter(),
        exporter.ExportProducts(productList, path),

        System.Console.WriteLine($"Export complete! File saved at {path}"),
    }
}

The resulting Excel file will have a bold header, correctly formatted currency, and perfectly sized columns - a much more professional and user-friendly report than the CSV. Best of all, it was created without needing Excel installed on the machine where the code runs.

GraphedGraphed

Still Building Reports Manually?

Watch how growth teams are getting answers in seconds — not days.

Watch Graphed demo video

For Full Control (With a Huge Warning): Using COM Interop

A third method exists: Office Interop. This involves adding a reference to the Microsoft Excel Object Library and programmatically "driving" the Excel application itself from your C# code. You can do anything a user could do manually - create charts, run macros, apply complex formulas, and more.

So why the huge warning? COM Interop requires the Microsoft Excel application to be installed on the exact same machine that is running your C# code. This makes it a terrible choice for web servers and other automated environments. It's also notoriously slow, consumes a lot of memory, and you risk leaving rogue Excel processes running in the background if your code isn’t perfect.

Generally, you should avoid this method for server-side applications. It is sometimes used for desktop applications or in controlled internal environments, but for most web and enterprise use cases, a library like ClosedXML is the superior choice.

Which Method Should You Choose?

Let's summarize to help you pick the right tool for the job.

For almost all modern development, the process is simple:

  • Use CSVs for quick, unformatted data dumps.
  • Use a NuGet Library like ClosedXML for all your professional reporting needs.

Final Thoughts

Exporting data to Excel from C# is a valuable skill that bridges the gap between your application and your business users. While a simple CSV export works in a pinch, using a modern library like ClosedXML gives you the power to create professional, formatted, and user-friendly reports that empower your team to make better decisions.

While coding these custom exports is powerful, the next step in efficiency is automating the entire analytics workflow. Instead of manually building new Excel reports every time a user has a question, imagine connecting your data sources once and letting your team explore insights in real-time. This is exactly why we built Graphed. Our platform connects directly to scores of data sources, allowing anyone on your team to create AI-powered dashboards and get answers just by asking questions in plain English - no exporting or developer time required.

Related Articles