Excel 生成 SQL 创建语句 create table

总共两张表,结构如下:

首先要把表结构转变为以下的一维结构, excel保存为 data_model.xlsx

table_name column_name data_type default comment
users uid bigint(10) NULL 用户ID
users uage int NULL 用户年龄
users uname varchar(30) NULL 用户姓名
users udescription varchar(50) NULL 描述
users lut datetime CURRENT_TIMESTAMP 最后更新时间
grades uid bigint(10) NULL 用户ID
grades subject varchar(30) NULL 科目
grades score decimal(18,2) NULL 分数
grades lut datetime CURRENT_TIMESTAMP 最后更新时间

Python 代码保存为excel2sql_create.py

import pandas as pd
data=pd.read_excel('data_model.xlsx')
data=data.fillna('NULL')
with open('./data_model.sql','w',encoding='utf8') as f:
    table_name=''
    for i,j in data.iterrows():    
        column_line=j.column_name+' '+j.data_type+' DEFAULT '+ j.default+' COMMENT \''+j.comment+'\'\n'
        if j.table_name == table_name:
            f.write('  ,'+column_line)
        else:
            if table_name!='':
                f.write(');\n\n')
            table_name=j.table_name
            f.writelines(['CREATE TABLE '+j.table_name+' (\n'
                         ,'  '+column_line])
    f.write(');')

工作目录中的文件: data_model.xlsx, excel2sql_create.py

最后在当前文件夹生成: data_model.sql, 内容是:

CREATE TABLE users (
  uid bigint(10) DEFAULT NULL COMMENT '用户ID'
  ,uage int DEFAULT NULL COMMENT '用户年龄'
  ,uname varchar(30) DEFAULT NULL COMMENT '用户姓名'
  ,udescription varchar(50) DEFAULT NULL COMMENT '描述'
  ,lut datetime DEFAULT CURRENT_TIMESTAMP COMMENT '最后更新时间'
);

CREATE TABLE grades (
  uid bigint(10) DEFAULT NULL COMMENT '用户ID'
  ,subject varchar(30) DEFAULT NULL COMMENT '科目'
  ,score decimal(18,2) DEFAULT NULL COMMENT '分数'
  ,lut datetime DEFAULT CURRENT_TIMESTAMP COMMENT '最后更新时间'
);
posted @ 2021-08-07 16:11  何大卫  阅读(799)  评论(0编辑  收藏  举报