Partage de technologie

Outil d'importation SQL vers Excel

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

Outil d'importation SQL vers Excel

Les étapes pour cette macro VBA sont les suivantes :

  1. Sélectionnez le fichier SQL via la boîte de dialogue de fichier.
  2. Lisez le contenu du fichier.
  3. Analysez chaque ligne du fichier et extrayez le nom de la table s'il contient "insérer dans".
  4. Vérifie si une feuille de calcul nommée nom de table existe déjà et crée une nouvelle feuille de calcul si elle n'existe pas.
  5. Insérez les données dans la feuille de calcul correspondante.

Conseil : Étant donné que les problèmes tels que le cas du texte SQL sont en réalité plus complexes, utilisez cet exemple avec prudence.
Certaines situations inattendues, telles que des champs contenant des) values Et ainsi de suite, c'est surtout un problème de positionnement, et ensuite de longueur de la valeur, au cas où il y aurait aussi quelque chose dans la valeur,Virgules, puis espaces et autres problèmes ;
Il devrait être plus facile d'utiliser Python ;
ce qui suitVBALe script est à titre de référence ; vous pouvez lier les boutons vous-même ;

Pour ce style :

insert into aaa (aa,bb,cc) values ('2','','3aa');
insert into aaa (aa,bb,cc) values ('1',null,'');
  • 1
  • 2
' +++++++++++++++++++++++++++++++++++++++++++++++++++
' author Mr.qyb_y
' Version 1.0.0
' Date 2024-07-09 21:10
' +++++++++++++++++++++++++++++++++++++++++++++++++++
Sub ImportSQLToExcel()
    Dim fd As FileDialog
    Dim filePath As String
    Dim fileContent As String
    Dim lines As Variant
    Dim line As Variant
    Dim sht As Worksheet
    Dim currentSheetIndex As Integer
    
    ' 创建文件对话框以选择SQL文件
    Set fd = Application.FileDialog(msoFileDialogFilePicker)
    fd.Title = "Select SQL File"
    fd.Filters.Add "SQL Files", "*.sql", 1
    
    If fd.Show = -1 Then
        filePath = fd.SelectedItems(1)
    Else
        MsgBox "No file selected.", vbExclamation
        Exit Sub
    End If
    
    ' 读取文件内容
    fileContent = ReadFileContent(filePath)
    lines = Split(fileContent, vbCrLf)
    
    currentSheetIndex = Sheets.Count
    
    ' 解析文件内容并插入到Excel中
    For Each line In lines
        If InStr(line, "insert into") > 0 Then
            Dim tableName As String
            Dim columnNames As String
            tableName = ExtractTableName(CStr(line)) ' 强制转换为字符串类型
            columnNames = ExtractColumnNames(CStr(line)) ' 提取列名
            
            ' 检查工作表是否已经存在
            On Error Resume Next
            Set sht = Sheets(tableName)
            On Error GoTo 0
            
            ' 如果工作表不存在,则创建新的工作表,并插入列名
            If sht Is Nothing Then
                Set sht = Sheets.Add(After:=Sheets(currentSheetIndex))
                sht.Name = tableName
                currentSheetIndex = currentSheetIndex + 1
                
                ' 插入列名
                InsertColumnNames sht, columnNames
            End If
            
            ' 插入数据
            InsertDataIntoSheet sht, CStr(line) ' 强制转换为字符串类型
        End If
    Next line
    
    MsgBox "Data imported successfully!", vbInformation
End Sub

Function ReadFileContent(filePath As String) As String
    Dim fileNumber As Integer
    Dim content As String
    fileNumber = FreeFile
    
    Open filePath For Input As fileNumber
    content = Input(LOF(fileNumber), fileNumber)
    Close fileNumber
    
    ReadFileContent = content
End Function

Function ExtractTableName(ByVal sqlLine As String) As String ' 明确指定参数类型
    Dim startPos As Integer
    Dim endPos As Integer
    startPos = InStr(sqlLine, "insert into") + Len("insert into ")
    endPos = InStr(startPos, sqlLine, " (")
    ExtractTableName = Trim(Mid(sqlLine, startPos, endPos - startPos))
End Function

Function ExtractColumnNames(ByVal sqlLine As String) As String
    Dim startPos As Integer
    Dim endPos As Integer
    startPos = InStr(sqlLine, "(") + 1
    endPos = InStr(sqlLine, ") values")
    ExtractColumnNames = Trim(Mid(sqlLine, startPos, endPos - startPos))
End Function

Sub InsertColumnNames(sht As Worksheet, columnNames As String)
    Dim columns As Variant
    columns = Split(columnNames, ",")
    
    With sht
        Dim i As Integer
        For i = LBound(columns) To UBound(columns)
            .Cells(1, i + 1).Value = Trim(columns(i))
        Next i
    End With
End Sub

Sub InsertDataIntoSheet(sht As Worksheet, ByVal sqlLine As String) ' 明确指定参数类型
    Dim valuesStartPos As Integer
    Dim valuesEndPos As Integer
    Dim values As String
    Dim data As Variant
    
    valuesStartPos = InStr(sqlLine, "values (") + Len("values (")
    valuesEndPos = InStr(valuesStartPos, sqlLine, ");")
    values = Mid(sqlLine, valuesStartPos, valuesEndPos - valuesStartPos)
    
    data = Split(values, ",")
    
    ' 去掉单引号并插入数据到工作表中
    With sht
        Dim nextRow As Long
        nextRow = .Cells(.Rows.Count, 1).End(xlUp).Row + 1
        
        Dim i As Integer
        For i = LBound(data) To UBound(data)
            .Cells(nextRow, i + 1).Value = Replace(Trim(data(i)), "'", "")
        Next i
    End With
End Sub

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127

🍀
bonne nuit
paix
allez