How to Convert a Data Table to an Excel File

In this tutorial, we explore the process of converting a data table into an Excel file programmatically using C# and the IronXL library. We begin by setting up a C# console application in Visual Studio, preferably using the latest version for optimal compatibility. After installing the IronXL library via the NuGet package manager or its website, we proceed to the program file.

The tutorial involves importing the IronXL library and System.Data namespace to handle data tables. A method is created to convert a data table into an Excel file, taking a file name as a parameter. We initialize a data table, define column headers, and input row data. A workbook object is then created with the Excel format, and a default worksheet is set up for data entry.

Using a loop, we insert data row by row into the worksheet, updating the cell values and incrementing the row count for new entries. Finally, the Excel file is saved using the "save as" function. The result is an Excel file generated from a data table, showcasing the simplicity and efficiency of the IronXL library for data manipulation and formatting. If further assistance is needed, a support team is available to help.

using System;
using System.Data;
using IronXL;

namespace DataTableToExcel
{
    class Program
    {
        static void Main(string[] args)
        {
            // Method call to convert DataTable to Excel
            ConvertDataTableToExcel("DataTable.xlsx");
        }

        /// <summary>
        /// Converts a DataTable to an Excel file.
        /// </summary>
        /// <param name="fileName">The name of the Excel file to save.</param>
        static void ConvertDataTableToExcel(string fileName)
        {
            // Initialize a new DataTable with columns
            DataTable table = new DataTable();
            table.Columns.Add("ID", typeof(int));
            table.Columns.Add("Name", typeof(string));
            table.Columns.Add("Age", typeof(int));

            // Populate the DataTable with sample data
            table.Rows.Add(1, "John Doe", 30);
            table.Rows.Add(2, "Jane Smith", 25);
            table.Rows.Add(3, "Sam Brown", 22);

            // Create a new workbook and get the first worksheet
            WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
            WorkSheet sheet = workbook.CreateWorkSheet("Sheet1");

            // Adding column headers
            for (int i = 0; i < table.Columns.Count; i++)
            {
                sheet[$"A{1}"].Value = table.Columns[i].ColumnName;
            }

            // Populate the worksheet with data table rows
            for (int rowIndex = 0; rowIndex < table.Rows.Count; rowIndex++)
            {
                for (int columnIndex = 0; columnIndex < table.Columns.Count; columnIndex++)
                {
                    sheet[$"{(char)('A' + columnIndex)}{(rowIndex + 2)}"].Value = table.Rows[rowIndex][columnIndex].ToString();
                }
            }

            // Save the workbook to the specified file
            workbook.SaveAs(fileName);
            Console.WriteLine($"Excel file '{fileName}' created successfully.");
        }
    }
}
using System;
using System.Data;
using IronXL;

namespace DataTableToExcel
{
    class Program
    {
        static void Main(string[] args)
        {
            // Method call to convert DataTable to Excel
            ConvertDataTableToExcel("DataTable.xlsx");
        }

        /// <summary>
        /// Converts a DataTable to an Excel file.
        /// </summary>
        /// <param name="fileName">The name of the Excel file to save.</param>
        static void ConvertDataTableToExcel(string fileName)
        {
            // Initialize a new DataTable with columns
            DataTable table = new DataTable();
            table.Columns.Add("ID", typeof(int));
            table.Columns.Add("Name", typeof(string));
            table.Columns.Add("Age", typeof(int));

            // Populate the DataTable with sample data
            table.Rows.Add(1, "John Doe", 30);
            table.Rows.Add(2, "Jane Smith", 25);
            table.Rows.Add(3, "Sam Brown", 22);

            // Create a new workbook and get the first worksheet
            WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
            WorkSheet sheet = workbook.CreateWorkSheet("Sheet1");

            // Adding column headers
            for (int i = 0; i < table.Columns.Count; i++)
            {
                sheet[$"A{1}"].Value = table.Columns[i].ColumnName;
            }

            // Populate the worksheet with data table rows
            for (int rowIndex = 0; rowIndex < table.Rows.Count; rowIndex++)
            {
                for (int columnIndex = 0; columnIndex < table.Columns.Count; columnIndex++)
                {
                    sheet[$"{(char)('A' + columnIndex)}{(rowIndex + 2)}"].Value = table.Rows[rowIndex][columnIndex].ToString();
                }
            }

            // Save the workbook to the specified file
            workbook.SaveAs(fileName);
            Console.WriteLine($"Excel file '{fileName}' created successfully.");
        }
    }
}
Imports System
Imports System.Data
Imports IronXL

Namespace DataTableToExcel
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			' Method call to convert DataTable to Excel
			ConvertDataTableToExcel("DataTable.xlsx")
		End Sub

		''' <summary>
		''' Converts a DataTable to an Excel file.
		''' </summary>
		''' <param name="fileName">The name of the Excel file to save.</param>
		Private Shared Sub ConvertDataTableToExcel(ByVal fileName As String)
			' Initialize a new DataTable with columns
			Dim table As New DataTable()
			table.Columns.Add("ID", GetType(Integer))
			table.Columns.Add("Name", GetType(String))
			table.Columns.Add("Age", GetType(Integer))

			' Populate the DataTable with sample data
			table.Rows.Add(1, "John Doe", 30)
			table.Rows.Add(2, "Jane Smith", 25)
			table.Rows.Add(3, "Sam Brown", 22)

			' Create a new workbook and get the first worksheet
			Dim workbook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
			Dim sheet As WorkSheet = workbook.CreateWorkSheet("Sheet1")

			' Adding column headers
			For i As Integer = 0 To table.Columns.Count - 1
				sheet($"A{1}").Value = table.Columns(i).ColumnName
			Next i

			' Populate the worksheet with data table rows
			For rowIndex As Integer = 0 To table.Rows.Count - 1
				For columnIndex As Integer = 0 To table.Columns.Count - 1
					sheet($"{ChrW(AscW("A"c) + columnIndex)}{(rowIndex + 2)}").Value = table.Rows(rowIndex)(columnIndex).ToString()
				Next columnIndex
			Next rowIndex

			' Save the workbook to the specified file
			workbook.SaveAs(fileName)
			Console.WriteLine($"Excel file '{fileName}' created successfully.")
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

Further Reading: How to Convert a Data Table to an Excel File

Regan Pun
Software Engineer
Regan graduated from the University of Reading, with a BA in Electronic Engineering. Before joining Iron Software, his previous job roles had him laser-focused on single tasks; and what he most enjoys at Iron Software is the spectrum of work he gets to undertake, whether it’s adding value to sales, technical support, product development or marketing. He enjoys understanding the way developers are using the Iron Software library, and using that knowledge to continually improve documentation and develop the products.
< PREVIOUS
How to Read Excel Data and Insert to Database Table in C#
NEXT >
How to Import CSV To Datatable in C#