图4 使用“添加引用”对话框添加对Excel 2003 PIAs的引用
在这个ADONET.vb Windows 窗体中BuildWorksheet被定义成一个私有过程,它有且只有一个DataSet参数。因为它实际上仅仅处理一个DataTable对象(存储客户数据),代码在开头处声明了一个名为dt的DataTable变量,用以保存对该表的引用。
Private Sub BuildWorksheet(ByVal ds As DataSet)
Dim dt As DataTable
为了维护Excel工作簿,需要实例化一个Excel应用程序对象,然后使用该对象模型添加一个新的工作簿,并更改工作簿的名字(例子中采用的是Northwind Customers),同时执行了其它UI方面的任务。
'Create an instance of Excel 2003, add a workbook,
'and let the user know what's happening
Dim xl As New Excel.Application
xl.Workbooks.Add()
xl.ActiveSheet.Name = "Northwind Customers"
xl.Visible = True
xl.Range("A1").Value = "Loading the DataSet...."
一旦加载并运行Excel,这段代码需要引用DataSet ds中的相应表(DataTable对象)。然后它遍历DataTable对象的列集合,将各个字段名写到工作表的首行。该示例使用Customers表和Customers列标题。
Try
xl.ScreenUpdating = False
'Start with the Customers table
dt = ds.Tables("Customers")
'Add the column headings for the Customers
Dim dc As DataColumn
Dim iCols As Int32 = 0
For Each dc In dt.Columns
xl.Range("A1").Offset(0, iCols).Value = dc.ColumnName
iCols += 1
Next
所有剩下的工作就是遍历表的所有行,使用DataRow对象的ItemArray属性来将每个数据行的内容写到工作表的一行中。这大约是Excel将要直接支持DataSet对象最显著的征兆。
'Add the data
Dim iRows As Int32
For iRows = 0 To dt.Rows.Count - 1
xl.Range("A2").Offset(iRows).Resize(1, iCols).Value = _
dt.Rows(iRows).ItemArray()
Next
Catch ex As Exception
这个过程中其余的代码更新UI,并对工作表应用内建的格式化。
Finally
xl.ScreenUpdating = True
End Try
'Make the sheet pretty
With xl.ActiveSheet.Range("A1")
.AutoFilter()
.AutoFormat(Excel.XlRangeAutoFormat.xlRangeAutoFormatSimple)
End With
xl = Nothing
End Sub
尽管Microsoft Office System本质上不支持.NET对象,但是DataSet的对象模型和功能使得将其结合到Microsoft Office System中,实现数据交互任务非常简单。
注意: 你可以放心使用这个技术,而不用担心DataSet来自何处,它甚至可以来自于.NET组件或Web服务。