Export DataTable from GridWeb

Exporting Worksheet Data

To a Specific DataTable

To export worksheet data to a specific DataTable object:

  1. Add the Aspose.Cells.GridWeb control to your Web Form.
  2. Create a specific DataTable object.
  3. Export the data of the selected cells to the specified DataTable object.

The example below creates a specific DataTable object with four columns. The worksheet data is exported starting from the first cell with all the rows and columns visible in the worksheet, to a DataTable object already created.

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// Creating a new DataTable object
DataTable dataTable = new DataTable();
// Adding specific columns to the DataTable object
dataTable.Columns.Add("Name", System.Type.GetType("System.String"));
dataTable.Columns.Add("Gender", System.Type.GetType("System.String"));
dataTable.Columns.Add("Age", System.Type.GetType("System.Int32"));
dataTable.Columns.Add("Class", System.Type.GetType("System.String"));
// Accessing the reference of the worksheet that is currently active
GridWorksheet sheet = GridWeb1.WorkSheets[GridWeb1.ActiveSheetIndex];
// Getting the total number of rows and columns inside the worksheet
int totalColumns = sheet.Cells.MaxColumn + 1;
int totalRows = sheet.Cells.MaxRow + 1;
// Exporting the data of the active worksheet to a specific DataTable object
dataTable = sheet.Cells.Export(0, 0, totalRows, totalColumns, true, true);
// Display exported data table in GridView
GridView1.DataSource = dataTable;
GridView1.DataBind();

To a New DataTable

Sometimes, you don’t want to create a DataTable object but simply need to export the worksheet data to a new DataTable object.

The example below tries a different way to show the use of the Export method. It takes the reference of the active worksheet and exports the complete data of that worksheet to a new DataTable object. The DataTable object can now be used in any way you want. For example, it is possible to bind the DataTable object to a GridView to view the data.

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// Accessing the reference of the worksheet that is currently active
GridWorksheet sheet1 = GridWeb1.WorkSheets[GridWeb1.ActiveSheetIndex];
// Getting the total number of rows and columns inside the worksheet
int totalColumns1 = sheet.Cells.MaxColumn + 1;
int totalRows1 = sheet.Cells.MaxRow + 1;
// Exporting the data of the active worksheet to a new DataTable object
DataTable dt = sheet.Cells.Export(0, 0, totalRows1, totalColumns1, true, true);
// Display exported data table in GridView
GridView2.DataSource = dataTable;
GridView2.DataBind();