How to Export Data from Excel to DataTable with Customization in C#
Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (173).NET Core  (29).NET MAUI  (199)Angular  (107)ASP.NET  (51)ASP.NET Core  (82)ASP.NET MVC  (89)Azure  (40)Black Friday Deal  (1)Blazor  (211)BoldSign  (13)DocIO  (24)Essential JS 2  (106)Essential Studio  (200)File Formats  (63)Flutter  (132)JavaScript  (219)Microsoft  (118)PDF  (80)Python  (1)React  (98)Streamlit  (1)Succinctly series  (131)Syncfusion  (892)TypeScript  (33)Uno Platform  (3)UWP  (4)Vue  (45)Webinar  (50)Windows Forms  (61)WinUI  (68)WPF  (157)Xamarin  (161)XlsIO  (35)Other CategoriesBarcode  (5)BI  (29)Bold BI  (8)Bold Reports  (2)Build conference  (8)Business intelligence  (55)Button  (4)C#  (146)Chart  (127)Cloud  (15)Company  (443)Dashboard  (8)Data Science  (3)Data Validation  (8)DataGrid  (62)Development  (618)Doc  (8)DockingManager  (1)eBook  (99)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (37)Extensions  (22)File Manager  (6)Gantt  (18)Gauge  (12)Git  (5)Grid  (31)HTML  (13)Installer  (2)Knockout  (2)Language  (1)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (497)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (42)Performance  (12)PHP  (2)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (12)Road Map  (12)Scheduler  (52)Security  (3)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (31)Solution Services  (4)Spreadsheet  (11)SQL  (10)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (12)Tips and Tricks  (112)UI  (379)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (2)Visual Studio  (31)Visual Studio Code  (17)Web  (582)What's new  (319)Windows 8  (19)Windows App  (2)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
Export Data from Excel to Data Tables with Customization in C#

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

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:

Enjoy a smooth experience with Syncfusion’s Excel Library! Get started with a few lines of code and without Microsoft or interop dependencies.

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;

Syncfusion’s C# Excel Library is meticulously documented with a multitude of code examples. Working with Excel files has never been simpler than this.

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);

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);
    
  • 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);
    

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();
    }
}

Witness the possibilities in demos showcasing the robust features of Syncfusion’s C# Excel Library.

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);

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

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

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();

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);

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();
    }
}

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";     
    }
}

GitHub samples

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

From simple data tables to complex financial models, Syncfusion empowers you to unleash your creativity and design stunning Excel spreadsheets.

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 PDFimageCSVTSV, HTMLcollections of objectsODS 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.

Please let us know in the comments below if you have any questions about these features. You can also contact us through our support forum, support portal, 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#

Tags:

Share this post:

Popular Now

Be the first to get updates

Subscribe RSS feed

Be the first to get updates

Subscribe RSS feed