Loading... # 引言 如果你表结构已经创建好了,然后你要写文档,需要数据库的表结构,这个小工具一定很适合你。 如果想导出excel,可以看之前写的文档 <div class="preview"> <div class="post-inser post box-shadow-wrap-normal"> <a href="https://www.zunmx.top/archives/1011/" target="_blank" class="post_inser_a no-external-link no-underline-link"> <div class="inner-image bg" style="background-image: url(https://www.zunmx.top/usr/uploads/2022/06/2521208573.png);background-size: cover;"></div> <div class="inner-content" > <p class="inser-title">pandas 多个excel合并并且分别创建新的sheet</p> <div class="inster-summary text-muted"> 引言项目需要代码import os import pandas sec = 0 with pandas.Excel... </div> </div> </a> <!-- .inner-content #####--> </div> <!-- .post-inser ####--> </div> <div class="preview"> <div class="post-inser post box-shadow-wrap-normal"> <a href="https://www.zunmx.top/archives/385/" target="_blank" class="post_inser_a no-external-link no-underline-link"> <div class="inner-image bg" style="background-image: url(https://www.zunmx.top/usr/uploads/2021/07/986692585.png);background-size: cover;"></div> <div class="inner-content" > <p class="inser-title">Pandas 输出表结构到Excel</p> <div class="inster-summary text-muted"> 引言开发一时爽,一直开发一直爽,但是到了写文档的时候,那就真的火葬场了,几百张表怎么写说明?不管是项目交接还是交付... </div> </div> </a> <!-- .inner-content #####--> </div> <!-- .post-inser ####--> </div> # 代码 ```python from sqlalchemy import create_engine import pandas import docx conn = create_engine('mysql+pymysql://数据库用户名:数据库密码@127.0.0.1/数据库名') def sqlQuery(sql): return pandas.read_sql_query(sql, conn) query = sqlQuery("""SELECT TABLE_NAME FROM information_schema.`COLUMNS` WHERE TABLE_SCHEMA = '数据库名' group by TABLE_NAME """) doc = docx.Document() for i in query.to_dict(orient='records'): cols = sqlQuery(f"""SELECT COLUMN_NAME as "字段名" , COLUMN_COMMENT as "字段解释" ,if(IS_NULLABLE='NO',"是","否") as 是否必填 FROM information_schema.`COLUMNS` WHERE TABLE_SCHEMA = '数据库名' and TABLE_NAME = '{i["TABLE_NAME"]}' """) doc.add_paragraph("表" + i["TABLE_NAME"]) table = doc.add_table(rows=1, cols=3, style='Table Grid') # 创建带边框的表格 hdr_cells = table.rows[0].cells # 获取第0行所有所有单元格 hdr_cells[0].text = '字段名' hdr_cells[1].text = '字段解释' hdr_cells[2].text = '是否必填' for i in cols.to_dict(orient='records'): cells = table.add_row().cells cells[0].text = i["字段名"] cells[1].text = i["字段解释"] cells[2].text = i["是否必填"] doc.save('d:/1/tmp.docx') ``` # 修改成你需要的 1. conn 连接字符串改成你mysql的 2. 所有的字符串 `数据库名` 替换成你的数据库名 3. 最后一行的路径改成你想保存的路径 # 导出效果 ![image.png](https://www.zunmx.top/usr/uploads/2022/08/277778050.png) © 允许规范转载 打赏 赞赏作者 支付宝微信 赞 如果觉得我的文章对你有用,请随意赞赏