excel 列名是数据表 的字段名 ,单元格的值 是数据表对应字段的值,生成sql插入语句

发布于:2024-12-20 ⋅ 阅读:(12) ⋅ 点赞:(0)

  1. 在 Excel 中,按 Alt + F11 打开 VBA 编辑器。
  2. 在菜单栏选择 插入 -> 模块,在新模块中粘贴以下代码。

VBA 代码

Sub GenerateSQLInsertStatementsToFile()
    Dim ws As Worksheet
    Dim lastRow As Long, lastCol As Long, i As Long, j As Long
    Dim sql As String, colNames As String, values As String
    Dim tableName As String
    Dim cellValue As String
    Dim filePath As String
    Dim fileNum As Integer

    ' 设置工作表
    Set ws = ActiveSheet  ' 使用当前活动的工作表
    tableName = "your_table_name"  ' 设置你的数据库表名
    filePath = "D:\file.txt"  ' 设置文件路径

    ' 打开文件
    fileNum = FreeFile()
    Open filePath For Output As #fileNum

    ' 获取数据范围
    lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
    lastCol = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column

    ' 构建列名字符串
    For j = 1 To lastCol
        If j > 1 Then colNames = colNames & ", "
        colNames = colNames & "[" & ws.Cells(1, j).Value & "]"
    Next j

    ' 遍历每一行
    For i = 2 To lastRow
        values = ""
        
        ' 遍历每一列
        For j = 1 To lastCol
            If j > 1 Then values = values & ", "
            
            ' 处理单引号以适应 SQL 语法
            cellValue = Replace(ws.Cells(i, j).Value, "'", "''")
            
            ' 值
            If IsNumeric(cellValue) Then
                values = values & cellValue
            Else
                values = values & "'" & cellValue & "'"
            End If
        Next j
        
        ' 构建 SQL 语句
        sql = "INSERT INTO " & tableName & " (" & colNames & ") VALUES (" & values & ");"
        
        ' 写入文件
        Print #fileNum, sql
    Next i

    ' 关闭文件
    Close #fileNum
End Sub

Excel 并按 Alt + F8,选择 GenerateSQLInsertStatementsToFile,然后点击 运行