How to Import or Export DataGrid to Excel or HTML files from your .NET applications?

Following example shows how to import or export DataGrid to XLS, XLSX, ODS, CSV or HTML files by using only GemBox.Spreadsheet .NET component.

GemBox.Spreadsheet is a C# / VB.NET component which provides simple and efficient way to read, write, convert and print native Microsoft Excel (XLSX, XLS) and other spreadsheet (ODS, CSV) formats and various document formats (HTML, PDF, XPS) from .NET applications without the need for Microsoft Excel on either the developer or client machines.
GemBox.Spreadsheet Free is free of charge while GemBox.Spreadsheet Professional is a commercial version licensed per developer.
For more information, see GemBox.Spreadsheet features and why GemBox.Spreadsheet outperforms Excel automation.

Example imports/exports DataGrid to Excel file (in XLS format) by working with DataGrid’s data source using InsertDataTable and ExtractToDataTable methods:

C# code:

// Load Excel file.
var workbook = ExcelFile.Load("Workbook.xls");

// Select active worksheet from the file.
var worksheet = workbook.Worksheets.ActiveWorksheet;

var dataTable = (DataTable)dataGrid.DataSource;

// Extract the data from the worksheet to DataGrid's data source starting at
// first row and first column for 10 rows or until the first empty row appears.
worksheet.ExtractToDataTable(dataTable,
new ExtractToDataTableOptions("A1", 10)
{
ExtractDataOptions = ExtractDataOptions.StopAtFirstEmptyRow
});

// Change the value of the first cell in the DataTable (DataGrid).
dataTable.Rows[0][0] = "Hello world!";

// Insert the data from DataTable to the worksheet starting at cell "A1".
worksheet.InsertDataTable(dataTable,
new InsertDataTableOptions("A1") { ColumnHeaders = true });

// Save the file to XLS format.
workbook.Save("DataGrid.xls");

Visual Basic .NET code:

' Load Excel file.
Dim workbook = ExcelFile.Load("Workbook.xls")

' Select active worksheet from the file.
Dim worksheet = workbook.Worksheets.ActiveWorksheet

Dim dataTable = DirectCast(dataGrid.DataSource, DataTable)

' Extract the data from the worksheet to DataGrid's data source starting at
' first row and first column for 10 rows or until the first empty row appears.
worksheet.ExtractToDataTable(dataTable,
New ExtractToDataTableOptions("A1", 10) With
{
.ExtractDataOptions = ExtractDataOptions.StopAtFirstEmptyRow
})

' Change the value of the first cell in the DataTable (DataGrid).
dataTable.Rows(0)(0) = "Hello world!"

' Insert the data from DataTable to the worksheet starting at cell "A1".
worksheet.InsertDataTable(dataTable,
New InsertDataTableOptions("A1") With {.ColumnHeaders = True})

' Save the file to XLS format.
workbook.Save("DataGrid.xls")

For a more detailed examples, see Import/Export DataTable samples from GemBox.Spreadsheet Sample Explorer.