DEV Community

loading...
Cover image for How to Export Data from Excel to DataTable with Customization in C#
Syncfusion, Inc.

How to Export Data from Excel to DataTable with Customization in C#

Suresh Mohan
Suresh is a Product Manager at Syncfusion and a technology enthusiast. He helps people follow best practices in coding and in using Syncfusion controls in their applications.
Originally published at syncfusion.com on ・8 min read

Exporting data from Excel to other formats lets users visualize the data according to their requirement. Syncfusion Excel Library (XlsIO) provides support to export worksheet data to data tables, collection objects, and nested class objects for handling the data efficiently.

In this blog, you will learn the steps to export data from:

Getting started

Step 1: Create a new C# console application in Visual Studio.

Create a New Console Application
Create a New Console Application

Step 2: Then, install the Syncfusion.XlsIO.WinForms NuGet package as a reference to the application from NuGet.org.

Install NuGet Package
Install NuGet Package

Step 3: Now, include the following namespaces in the Program.cs file.

using Syncfusion.XlsIO;
using System.Data;
using System.IO;
using System.Reflection;
Enter fullscreen mode Exit fullscreen mode

Export to DataTable

The project is ready! Let’s add the code that exports data from Excel to a DataTable. The ExportDataTable() method in XlsIO allows you to do this:

Step 1: Open or create an Excel spreadsheet using the Excel engine in XlsIO. This is the source spreadsheet from which we are going to export data to a DataTable. Here, we are opening an existing Excel document with data.

ExcelEngine excelEngine = new ExcelEngine();
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Xlsx;

FileStream inputStream = new FileStream("Sample.xlsx", FileMode.Open, FileAccess.Read);
IWorkbook workbook = application.Workbooks.Open(inputStream);

Enter fullscreen mode Exit fullscreen mode

Step 2: Then, add the code to export the data from Excel to a DataTable. There are two overloads to perform this operation:

  • ExportDataTable (IRange dataRange, ExcelExportDataTableOptions options): This overload allows you to specify the range of data to be exported along with the export options. The following code example exports data from the specified range to the DataTable.
//Export data from the specified range to the DataTable.
DataTable customersTable = worksheet.ExportDataTable(worksheet.UsedRange, ExcelExportDataTableOptions.ColumnNames);

Enter fullscreen mode Exit fullscreen mode
  • ExportDataTable (int firstRow, int firstColumn, int maxRows, int maxColumns, ExcelExportDataTableOptions options): This overload allows you to specify the rows and columns of the data to be exported along with the export options. We should define the start and end rows and columns in this method.
//Export data from the first row and first column, up to the 10th row and 10th column of the Excel worksheet to the data table.
DataTable customersTable = worksheet.ExportDataTable(1, 1, 10, 10, ExcelExportDataTableOptions.ColumnNames);

Enter fullscreen mode Exit fullscreen mode

The following complete code snippet illustrates how to export data from Excel to a DataTable.

static void Main(string[] args)
{
    using (ExcelEngine excelEngine = new ExcelEngine())
    {
        IApplication application = excelEngine.Excel;
        application.DefaultVersion = ExcelVersion.Xlsx;
        FileStream inputStream = new FileStream("Sample.xlsx", FileMode.Open, FileAccess.Read);
        IWorkbook workbook = application.Workbooks.Open(inputStream);
        IWorksheet worksheet = workbook.Worksheets[0];

        //Read data from the worksheet and export to the DataTable.
        DataTable customersTable = worksheet.ExportDataTable(worksheet.UsedRange, ExcelExportDataTableOptions.ColumnNames);

        //Save the workbook as stream.
        FileStream stream = new FileStream("ExportToDT.xlsx", FileMode.Create, FileAccess.ReadWrite);
        workbook.SaveAs(stream);
        stream.Dispose();
    }
}

Enter fullscreen mode Exit fullscreen mode

Export to DataTable with customization

So, we have learned to export the data from Excel to a DataTable. Now, let’s focus on customizing the data during the export. The following are different customization options available when exporting the data to a DataTable:

  • Modify the value of a cell in the DataTable.
  • Skip specific rows.
  • Stop the data export.

The modifications made will only be reflected in the DataTable, and the data in the Excel spreadsheet will remain the same.

The ExportDataTableEvent will be triggered when exporting data from each cell. This event helps in performing the following actions using the ExportDataTableActions enumeration:

  • Default: Exports worksheet data to the DataTable without any action.
  • SkipRows: Exports worksheet data to the DataTable by skipping specific rows.
  • StopExporting: Stops exporting the data from the Excel worksheet to the DataTable.

The following steps show how to export data from an Excel worksheet to a DataTable with customization:

Step 1: Open or create an Excel document using the Excel engine in XlsIO. Here, we are opening an existing Excel document with data.

Note: Follow the Getting Started section to create a project with the NuGet packages.

ExcelEngine excelEngine = new ExcelEngine();
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Xlsx;

FileStream inputStream = new FileStream("Sample.xlsx", FileMode.Open, FileAccess.Read);
IWorkbook workbook = application.Workbooks.Open(inputStream);

Enter fullscreen mode Exit fullscreen mode

Step 2: Then, create an event handler method in the class.

private void ExportDataTable_EventAction(ExportDataTableEventArgs e)
{
   //Event handler code should be placed here.
}

Enter fullscreen mode Exit fullscreen mode

Step 3: Now, bind the event handler with ExportDataTableEvent in IWorksheet.

//Event to choose an action while exporting data from Excel to DataTable.
//The event will be triggered at this line while exporting data from each cell in the Excel worksheet.
worksheet.ExportDataTableEvent += ExportDataTable_EventAction();

Enter fullscreen mode Exit fullscreen mode

Step 4: Finally, export worksheet data using the ExportDataTable method.

//Read data from the worksheet and exports to the DataTable.
DataTable customersTable = worksheet.ExportDataTable(worksheet.UsedRange, ExcelExportDataTableOptions.ColumnNames);

Enter fullscreen mode Exit fullscreen mode

The following is the complete code example of how to export data from an Excel worksheet to a DataTable by triggering an event to customize the export.

static void Main(string[] args)
{
    using (ExcelEngine excelEngine = new ExcelEngine())
    {
        IApplication application = excelEngine.Excel;
        application.DefaultVersion = ExcelVersion.Xlsx;
        FileStream inputStream = new FileStream("Sample.xlsx", FileMode.Open, FileAccess.Read);
        IWorkbook workbook = application.Workbooks.Open(inputStream);
        IWorksheet worksheet = workbook.Worksheets[0];

        //Event to choose an action while exporting data from Excel to DataTable.
        //The event will be triggered at this line while exporting data from each cell in the Excel worksheet.
        worksheet.ExportDataTableEvent += ExportDataTable_EventAction();

        //Read data from the worksheet and export to the DataTable.
        DataTable customersTable = worksheet.ExportDataTable(worksheet.UsedRange, ExcelExportDataTableOptions.ColumnNames);

        //Saving the workbook as stream.
        FileStream stream = new FileStream("ExportToDT.xlsx", FileMode.Create, FileAccess.ReadWrite);
        workbook.SaveAs(stream);
        stream.Dispose();
    }
}

Enter fullscreen mode Exit fullscreen mode

The following code is the event handler for the previous code.

private void ExportDataTable_EventAction(ExportDataTableEventArgs e)
{
    if (e.ExcelValue != null && e.ExcelValue.ToString() == "Owner")
    {
        //Skips the row to export into the DataTable if the Excel cell value is “Owner”.
        e.ExportDataTableAction = ExportDataTableActions.SkipRow;    
    }
    else if (e.DataTableColumnIndex == 0 && e.ExcelRowIndex == 5 && e.ExcelColumnIndex == 1)
    {
        //Stops the export based on the condition.
        e.ExportDataTableAction = ExportDataTableActions.StopExporting;   
    }
    else if (e.ExcelValue != null && e.ExcelValue.ToString() == "Mexico D.F.")
    {
        //Replaces the cell value in the DataTable without affecting the Excel document.
        e.DataTableValue = "Mexico";     
    }
}

Enter fullscreen mode Exit fullscreen mode

GitHub samples

For more information, refer to the export data from Excel to a DataTable with customization demo project.

Conclusion

As you can see, the Syncfusion Excel Library (XlsIO) provides support to export data from Excel to DataTable with customization options. Take a moment to peruse the documentation, where you’ll find other options and features, all with accompanying code samples. Using the library, you can also export Excel data to PDF, image, CSV, TSV, HTML, collections of objects, ODS and JSON file formats, and more.

If you are new to our Excel Library, it is highly recommended that you follow our Getting Started guide.

Are you already a Syncfusion user? You can download the product setup. If you’re not yet a Syncfusion user, you can download a free, 30-day trial.

If you have any questions about these features, please let us know in the comments below. You can also contact us through our support forum, Direct-Trac, or feedback portal. We are happy to assist you!

Related blogs

  1. 6 Easy Ways to Export Data to Excel in C#
  2. How to Export Data from SQL Server to Excel Table in C#
  3. Export Data from Collection to Excel and Group It in C#
  4. Export Data to a Predefined Excel Template in C#
  5. Easy Steps to Export HTML Tables to an Excel Worksheet in C#

Discussion (0)