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

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

VBA 代码

vbnet 复制代码
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,然后点击 运行

相关推荐
想睡好7 分钟前
express中间件(java拦截器)
java·中间件·express
Wang's Blog8 分钟前
Linux小课堂: CentOS 7 Minimal 服务器安装与网络配置实战详解
linux·服务器·centos
兢兢业业的小白鼠10 分钟前
Java常用中间件整理讲解——Redis,RabbitMQ
java·中间件·java-rabbitmq·1024程序员节
鱼儿也有烦恼14 分钟前
快速学完 LeetCode top 1~50 [特殊字符]
java·算法·leetcode·1024程序员节
独自破碎E15 分钟前
LeetCode 380: O(1) 时间插入、删除和获取随机元素
java·算法·leetcode
信仰_27399324318 分钟前
Mybatis一级缓存
java·缓存·mybatis
Brookty25 分钟前
【算法】前缀和(二)使用
java·学习·算法·前缀和·动态规划·1024程序员节
小范同学_26 分钟前
Spring集成WebSocket
java·spring boot·websocket·spring·1024程序员节
华纳云IDC服务商34 分钟前
服务器实时流量监控工具推荐:确保服务器不被滥用
服务器·流量监控
tritone37 分钟前
在优豆云免费云服务器上搭建与配置Apache的实践笔记
服务器·网络·apache·1024程序员节