从DataTable导入数据到Grid
Contents
[
Hide
]
自.NET框架发布以来,微软已经提供了一种优秀的方式,以DataTable对象的形式在离线模式下存储数据。为了满足开发者的需求,Aspose.Cells.GridDesktop也支持从数据表中导入数据。本主题讨论了如何做到这一点。
示例
使用Aspose.Cells.GridDesktop控件导入数据表内容:
- 将Aspose.Cells.GridDesktop控件添加到表单中。
- 创建包含要导入的数据的DataTable对象。
- 获取所需工作表的引用。
- 将数据表内容导入工作表。
- 根据数据表的列名设置工作表的列标题。
- 如有需要,设置列的宽度。
- 显示工作表。
在下面的示例中,我们创建了一个DataTable对象,并填充了一些来自名为Products的数据库表的数据。最后,我们使用Aspose.Cells.GridDesktop从该DataTable对象导入数据到所需的工作表。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; |