在.NET开发平台下经常使用DataTable对象来存储数据,所以
Aspose.Cells.GridDesktop表格控件支持从DataTable导入数据,也可以把表格里的数据导出到DataTable,这篇文章主要介绍怎么快速实现
Aspose.Cells.GridDesktop表格数据的导入导出,具体如下:
2.创建一个DataTable对象并且把数据设置好
3.导入数据到工作表
4.根据DataTable里的列名设置好Worksheet里的列名
//Creating DataTable object
DataTable dt = new DataTable();
//Setting the SQL Query of an already created OleDbCommand object
this.oleDbSelectCommand1.CommandText = @"SELECT * FROM Products ORDER BY Product_Id";
//Filling DataTable using an already created OleDbDataAdapter object
this.oleDbDataAdapter1.Fill(dt);
//Accessing the reference of a worksheet
Worksheet sheet = gridDesktop1.Worksheets[0];
//Importing data from DataTable to the worksheet. O,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
gridDesktop.ActiveSheetIndex = 0;
从Aspose.Cells.GridDesktop表格中导出数据到DataTable方法基本上跟导入差不多,首先也是需要根据自己的需求创建好要接受数据的DataTable对象,然后从表格中指定列导出
//Creating a new DataTable object
DataTable dataTable = new DataTable();
//Adding specific columns to the DataTable object
dataTable.Columns.Add("ProductName", System.Type.GetType("System.String"));
dataTable.Columns.Add("CategoryName", System.Type.GetType("System.String"));
dataTable.Columns.Add("QuantityPerUnit", System.Type.GetType("System.String"));
dataTable.Columns.Add("UnitsInStock", System.Type.GetType("System.Int32"));
//Exporting the data of the first worksheet of the Grid to the specific
//DataTable object
dataTable = gridDesktop1.Worksheets[0].ExportDataTable(dataTable, 0, 0, 69, 4, true);