合并数据

假定有一个下图所示的Excel格式的订单表:

需要将其数据合并到Foxtable的订单表中,可以参考以下代码:

Dim Book As New XLS.Book("c:\test\订单.xls")
Dim
Sheet As XLS.Sheet = Book.Sheets(0)
Tables("订单").StopRedraw()
'注意以下数组中列名称的顺序,必须和Excel表中的列顺序一致
Dim
nms() As String = {"编号","产品","客户","雇员","单价","折扣","数量","日期"}
'注意下面的循环变量从1开始,而不是从0开始,因为Excel表的第一行是标题
For n As Integer = 1 To Sheet.Rows.Count -1
    Dim
r As Row = Tables("订单").AddNew()
    For
m As Integer = 0 To nms.Length - 1
        
r(nms(m)) = Sheet(n,m).Value
    Next
Next
Tables(
"订单").ResumeRedraw()

如果订单表中已经存在相同编号的订单,那么就跳过此订单,可以将代码改为:

Dim Book As New XLS.Book("c:\test\订单.xls")
Dim
Sheet As XLS.Sheet = Book.Sheets(0)
Tables(
"订单").StopRedraw()
'注意以下数组中列名称的顺序,必须和Excel表中的列顺序一致

Dim
nms() As String = {"编号","产品","客户","雇员","单价","折扣","数量","日期"}
'注意下面的循环变量从1开始,而不是从0开始,因为Excel表的第一行是标题

For
n As Integer = 1 To Sheet.Rows.Count -1
   
Dim bh As String = sheet(n,0).Text
   
If DataTables("订单").Find("编号 = '" & bh & "'") Is Nothing Then '如果不存在同编号的订单
        Dim
r As Row = Tables("订单").AddNew()
        For
m As Integer = 0 To nms.Length - 1
           
r(nms(m)) = Sheet(n,m).Value
       
Next
    End If
Next
Tables(
"订单").ResumeRedraw()

再进一步,如果存在相同编号的订单,则覆盖原来的订单,否则新增一个订单,代码为:

Dim Book As New XLS.Book("c:\test\订单.xls")
Dim
Sheet As XLS.Sheet = Book.Sheets(0)
Tables(
"订单").StopRedraw()
Dim
nms() As String = {"编号","产品","客户","雇员","单价","折扣","数量","日期"}
For
n As Integer = 1 To Sheet.Rows.Count -1
   
Dim bh As String = sheet(n,0).Text
   
Dim dr As DataRow = DataTables("订单").Find("编号 = '" & bh & "'")
    If
dr Is Nothing Then '如果不存在同编号的订单
       
dr =  DataTables("订单").AddNew()
    End If
    For
m As Integer = 0 To nms.Length - 1
       
dr(nms(m)) = Sheet(n,m).Value
    Next
Next
Tables(
"订单").ResumeRedraw()

提示:其实我们用Merger合并数据会更加简单,上述代码的目的是给大家提供另一种思路,因为在一些特殊情况下,Merger可能无法正常合并数据。


本页地址:http://www.foxtable.com/webhelp/topics/2334.htm