Importazione dei dati da un DataTable a una Griglia

Contents
[ ]

Esempio

Per importare i contenuti di una tabella dati utilizzando il controllo Aspose.Cells.GridDesktop:

  1. Aggiungi il controllo Aspose.Cells.GridDesktop a un modulo.
  2. Crea un oggetto DataTable che contiene i dati da importare.
  3. Ottenere il riferimento di un foglio di lavoro desiderato.
  4. Importa i contenuti della tabella dati nel foglio di lavoro.
  5. Imposta gli headers delle colonne del foglio di lavoro in base ai nomi delle colonne della tabella dati.
  6. Imposta la larghezza delle colonne, se desiderato/
  7. Visualizza il foglio di lavoro.

Nell’esempio qui riportato, abbiamo creato un oggetto DataTable e lo abbiamo riempito con alcuni dati ottenuti da una tabella del database chiamata Prodotti. Infine, abbiamo importato i dati da quell’oggetto DataTable in un foglio di lavoro desiderato utilizzando Aspose.Cells.GridDesktop.

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// The path to the documents directory.
string dataDir = Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
OleDbDataAdapter adapter;
DataTable dt = new DataTable();
// Creating connection string to connect with database
string conStr = @"Provider=microsoft.jet.oledb.4.0;Data Source=" + dataDir + "dbDatabase.mdb";
// Creating Select query to fetch data from database
string query = "SELECT * FROM Products ORDER BY ProductID";
adapter = new OleDbDataAdapter(query, conStr);
// Filling DataTable using an already created OleDbDataAdapter object
adapter.Fill(dt);
// Accessing the reference of a worksheet
Worksheet sheet = gridDesktop1.Worksheets[0];
// Importing data from DataTable to the worksheet. 0,0 specifies to start importing data from the cell with first row (0 index) and first column (0 index)
sheet.ImportDataTable(dt, false, 0, 0);
// Iterating through the number of columns contained in the DataTable
for (int i = 0; i < dt.Columns.Count; i++)
{
// Setting the column headers of the worksheet according to column names of the DataTable
sheet.Columns[i].Header = dt.Columns[i].Caption;
}
// Setting the widths of the columns of the worksheet
sheet.Columns[0].Width = 240;
sheet.Columns[1].Width = 160;
sheet.Columns[2].Width = 160;
sheet.Columns[3].Width = 100;
// Displaying the contents of the worksheet by making it active
gridDesktop1.ActiveSheetIndex = 0;