有時(shí)候需要將Excel文件中的數(shù)據(jù)導(dǎo)入到數(shù)據(jù)庫(kù)中,常用的做法是使用程序讀取Excel,然后存入數(shù)據(jù)庫(kù);這里換一個(gè)方法,用Excel生成SQL語(yǔ)句,然后用這些SQL語(yǔ)句來(lái)更新數(shù)據(jù)庫(kù)。
本文主要說(shuō)明Excel如何使用VB宏構(gòu)造需要的SQL語(yǔ)句,并生成文件。 2、如何添加按鈕:
依次打開:視圖–工具欄–控件工具箱,選擇“命令按鈕”,自己畫一個(gè)就行了; 依次打開:右鍵–屬性,可以修改名稱、樣式等。 具體操作可以上網(wǎng)找找。 3、如何使用VB宏:
依次打開:工具–宏–安全性,看看你的Excel是否允許使用“宏”。 然后打開:工具–宏–Visual Basic 編輯器,雙擊左側(cè)的“Sheet1”,然后在右側(cè)的代碼區(qū)域粘貼如下代碼: '最大行數(shù)
Const MAX_NUM_ROW = 5000 '導(dǎo)出文件路徑所在單元格
Const PATH_OUTPUT_ROW = 3 Const PATH_OUTPUT_COL = 3 '定義列常量
Const NAME_COL = 1 Const GENDER_COL = 2 Const PHONE_COL = 3 Const EMAIL_COL = 4 '讀取數(shù)據(jù)開始行數(shù)
Const START_ROW = 5 '定義數(shù)據(jù)實(shí)體類
Private Type Tmplt NAME As String GENDER As String PHONE As String EMAIL As String End Type '行數(shù)變量
Dim noOfTmplts As Integer '數(shù)據(jù)實(shí)體類數(shù)組
Dim TmpltArray(MAX_NUM_ROW) As Tmplt '點(diǎn)擊按鈕觸發(fā)事件
Private Sub CommandButton1_Click() generateSQL End Sub '生成SQL
Private Sub generateSQL() makedir initData writeToFile End Sub '構(gòu)建文件輸出路徑
Private Sub makedir() On Error Resume Next MkDir Sheet1.Cells(PATH_OUTPUT_ROW, PATH_OUTPUT_COL) End Sub '讀取Excel數(shù)據(jù),填充實(shí)體類數(shù)組
Private Sub initData() Erase TmpltArray
noOfTmplts = 0 Dim j As Integer
'循環(huán)讀取Excel數(shù)據(jù)行
For j = START_ROW To MAX_NUM_ROW TmpltArray(noOfTmplts).NAME = Sheet1.Cells(j, NAME_COL)
TmpltArray(noOfTmplts).GENDER = Sheet1.Cells(j, GENDER_COL) TmpltArray(noOfTmplts).PHONE = Sheet1.Cells(j, PHONE_COL) TmpltArray(noOfTmplts).EMAIL = Sheet1.Cells(j, EMAIL_COL) noOfTmplts = noOfTmplts + 1 Next
End Sub '讀取實(shí)體類數(shù)組,生成SQL并寫入文件
Private Sub writeToFile() Dim lvOutputPath As String
'輸出文件路徑
lvOutputPath = Sheet1.Cells(PATH_OUTPUT_ROW, PATH_OUTPUT_COL) If lvOutputPath = "" Then
MsgBox "沒(méi)有找到輸出文件路徑!" Exit Sub End If fileNum = FreeFile
'打開輸出文件
Open lvOutputPath For Output As fileNum Dim lvUserSql As String Dim nameStr As String Dim genderStr As String Dim phoneStr As String Dim emailStr As String '循環(huán)生成SQL
For j = 0 To noOfTmplts - 1 nameStr = TmpltArray(j).NAME
genderStr = TmpltArray(j).GENDER phoneStr = TmpltArray(j).PHONE emailStr = TmpltArray(j).EMAIL If nameStr <> "" Then
lvUserSql = "Insert into Students(name,gender,phone,email) values('" & nameStr & "','" & genderStr & "','" & phoneStr & "','" & emailStr & "');" Print #fileNum, lvUserSql End If Next Close fileNum
MsgBox "文件生成完成!"
Exit Sub
Err_Open_File:
Close lvFileNum If Err.Number = 76 Then
'路徑未找到 MsgBox Err.Description Exit Sub Else
MsgBox Err.Description Exit Sub End If End Sub
OK,這樣就可以了!點(diǎn)擊你的按鈕,看看生成文件了嗎?
如果按鈕還是編輯狀態(tài),關(guān)了再打開就行了。 |
|