Copied RSS Feed

Excel

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

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

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#

Meet the Author

Johnson Manohar

Johnson Manohar is a Product Manager for XlsIO in Syncfusion Software. He is passionate about managing and delivering quality products. He is a music composer and has released various album titles.