一键导出数据库结构,每个表的“序号“, “字段名“, “类型“, “长度“, “默认值“, “是否为空“, “主键“, “说明“

#安装python-docx
pip install python-docx
#安装SQLAlchemy
pip install SQLAlchemy==1.4.39
from docx import Document
from docx.shared import Pt, Cm
from docx.oxml.ns import qn
from docx.enum.table import WD_TABLE_ALIGNMENT
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx.shared import RGBColor
import os
from sqlalchemy import create_engine, MetaData

table_header = ["序号", "字段名", "类型", "长度", "默认值", "是否为空", "主键", "说明"]


def read_table_struct():
    # 连接到数据库,替换为你的数据库信息
    from urllib.parse import quote_plus as urlquote
    db_url = f'mysql://root:{urlquote("<密码>")}@<post>/<数据库>'
    engine = create_engine(db_url)

    # 创建元数据对象
    metadata = MetaData(bind=engine)
    metadata.reflect()

    # 获取数据库中所有的表
    tables = metadata.tables
    transfer_to_word_tabel(tables)

    # 关闭数据库连接
    engine.dispose()


def transfer_to_word_tabel(mySQL_tables):
    # 新建一个文档
    doc = Document()
    # # 添加一个表格,设置行数和列数
    # 遍历表并打印表结构
    for table_name in mySQL_tables.keys():
        print(f"Table: {table_name}")
        doc.add_paragraph(f"Table: {table_name}")
        mySQL_table = mySQL_tables[table_name]
        print("=" * 30)
        num_rows = len(mySQL_table.columns) + 1
        num_cols = 8
        table = doc.add_table(rows=num_rows, cols=num_cols)

        # 获取表格的第一行作为表头
        header_row = table.rows[0]

        i = 0

        # 设置表头的样式
        for cell in header_row.cells:
            cell.text = table_header[i]
            i = i + 1
            cell.paragraphs[0].alignment = 1  # 居中对齐
            cell.paragraphs[0].runs[0] = table.style.font
            cell.paragraphs[0].runs[0].name = "仿宋"  # 设置字体为仿宋
            cell.paragraphs[0].runs[0].bold = True  # 设置为粗体
            cell.paragraphs[0].runs[0].size = Pt(12)  # 设置字体大小

        # 设置表格框线样式
        table.style = 'Table Grid'  # 设置为内部框线样式

        # 设置表格的对齐方式
        table.alignment = WD_TABLE_ALIGNMENT.CENTER  # 居中对齐

        # 设置表格字体样式
        table_font = table.style.font
        table_font.name = 'Times New Roman'  # 设置字体名称
        table_font.size = Pt(12)  # 设置字体大小

        # 遍历表格的行和列,填充内容
        serial_num = 0
        for row in table.rows[1:]:
            table_struct = parse_table_struct(mySQL_table.columns[serial_num])
            for i in range(8):
                cell = row.cells[i]
                if i == 0:
                    cell.text = str(serial_num + 1)
                elif i == 1:
                    cell.text = table_struct["column_name"]
                elif i == 2:
                    cell.text = table_struct["column_type"].lower()
                elif i == 3:
                    cell.text = table_struct["column_length"]
                elif i == 4:
                    cell.text = table_struct["column_default"]
                elif i == 5:
                    cell.text = table_struct["column_nullable"]
                elif i == 6:
                    cell.text = table_struct["column_main_key"]
                elif i == 7:
                    cell.text = table_struct["column_comment"]
                    font = cell.paragraphs[0].runs[0].font
                    font.name = "仿宋"
                cell_font = cell.paragraphs[0].runs[0].font  # 获取单元格的字体
                cell_font.bold = False  # 设置为粗体

                # 获取单元格的段落
                paragraph = cell.paragraphs[0]

                # 设置垂直居中
                paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER

                # 创建一个段落格式对象
                paragraph_format = paragraph.paragraph_format

                # 设置段落的行间距为 1.5
                paragraph_format.line_spacing = 1.5





            serial_num = serial_num + 1

        # 添加一个段落,包含换行
        doc.add_paragraph("\n")

    # 保存文档
    doc.save("example.docx")


def parse_table_struct(column):
    column_nullable = "YES" if column.nullable else "NO"
    column_default = column.default.arg if column.default is not None else ""
    column_main_key = "YES" if column.primary_key else "NO"
    column_comment = column.comment if column.comment else ""

    column_type = str(column.type)
    column_length = None
    if "(" in column_type and ")" in column_type:
        column_length = column_type[column_type.index("(") + 1:column_type.index(")")]
    column_length = column_length if column_length is not None else ""
    column_type = repr(column.type).split("(")[0]  # 去掉字符集部分
    return {
        "column_name": column.name,
        "column_type": column_type,
        "column_length": column_length,
        "column_default": column_default,
        "column_nullable": column_nullable,
        "column_main_key": column_main_key,
        "column_comment": column_comment
    }


if __name__ == '__main__':
    read_table_struct()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值