代码在自定义函数里:
Dim str,drl,sheetname As String
Dim dt As DataTable
Select Case args.Length
Case 2
dt = DataTables(args(0))
drl = args(1)
Case 3
dt = DataTables(args(0))
drl = args(1)
sheetname = args(2)
End Select
Dim Result As DialogResult
Result = MessageBox.Show("要导入excel吗?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If Result = DialogResult.Yes Then
Dim dlg As New OpenFileDialog
dlg.Filter = "Excel文件|*.xls;*.xlsx"
dlg.MultiSelect = True
If dlg.ShowDialog =DialogResult.OK Then
Dim stt As Date = Date.Now '开始计时
try
Dim App As New MSExcel.Application
systemready = False
Dim Wb As MSExcel.WorkBook = App.WorkBooks.Open(dlg.FileName)
Dim Ws As MSExcel.WorkSheet
If args.length = 2 Then Ws = Wb.WorkSheets(1)
If args.length > 2 Then Ws = Wb.WorkSheets(sheetname)
wb.saved = True
Dim Rg As MSExcel.Range = Ws.UsedRange
Dim ary = rg.value
dt.ResumeRedraw()
dt.StopRedraw()
Dim nms As New Dictionary(Of String, Integer)
Dim dic As new Dictionary(Of Integer,DataRow)
Dim ls As new List(Of Integer)
For c As Integer = 1 To Rg.Columns.count
If dt.DataCols.Contains(ary(1,c).replace(" ", "")) Then
nms.Add(ary(1,c).replace(" ", ""), c)
End If
Next
Dim flag As Boolean = True
For n As Integer = 2 To Rg.Rows.count
Dim sfzhm As String = ary(n,nms(drl))
If sfzhm = "" Then Continue For
Dim dr As DataRow = dt.Find(drl & " ='" & sfzhm & "'")
If dr IsNot Nothing Then
Result = MessageBox.Show("重复要覆盖?"& vbcrlf &"是---覆盖导入"& vbcrlf &"否---新增导入", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If Result = DialogResult.Yes Then
flag = True
Else
flag = False
End If
Exit For
End If
Next
For n As Integer = 2 To Rg.Rows.count
Dim sfzhm As String = ary(n,nms(drl))
If sfzhm = "" Then Continue For
Dim dr As DataRow = dt.Find(drl & " ='" & sfzhm & "'")
If dr Is Nothing Then
dic.Add(n,Nothing)
ElseIf flag = True
dic.Add(n,dr)
End If
Next
For Each l As Integer In dic.Keys
Dim ndr As DataRow
If dic(l) Is Nothing Then
ndr = dt.AddNew
Else
ndr = dic(l)
End If
For Each m As String In nms.keys
If dt.DataCols(m).IsBoolean Then
If ary(l,nms(m))= "" OrElse ary(l,nms(m))= "False" OrElse ary(l,nms(m))= 0 Then
ndr (m) = False
Else
ndr (m) = True
End If
Else If dt.DataCols(m).Expression > "" Then
Else If dt.DataCols(m).IsNumeric Then
ndr (m) = val(ary(l,nms(m)))
Else If dt.DataCols(m).IsDate Then
Dim d As Date
If Date.TryParse(ary(l,nms(m)), d)
ndr (m) = d
End If
Else
ndr (m) = ary(l,nms(m))
End If
Next
Next
dt.ResumeRedraw()
Dim n1,n2 As Integer
For Each l As Integer In dic.Keys
Dim ndr As DataRow
If dic(l) Is Nothing Then
n1+= 1
Else
n2+= 1
End If
Next
MessageBox.Show("新增:" & n1 & vbcrlf & vbcrlf & "更新:" & n2 & vbcrlf & vbcrlf & "耗时:" & (Date.Now - stt).TotalSeconds & "秒","提示")
app.quit
catch ex As exception
msgbox("导入失败")
End try
SystemReady = True
End If
End If