思路: 1.使用DocxTemplate库对word文件进行操作;
2.在数据库中创建临时表,表内容为该用户下面所有的表,并且加上序号和状态两个字段,语句如下:
创建临时表create table BALL AS select T.*,ROWNUM PAGES,'0' STATUS from user_tab_comments T;
3.循环查询临时表ball状态等于0的行,跑出行对应的表的所有字段信息写入word;
4.写入完成后改变ball该行的状态值为1,表明该行处理完毕;
word模板是 :
描述:{{bzs}}
表 {{page}} {{tablename}}
序号 | 字段名称 | 字段描述 | 字段类型 | 长度 | 允许空 | 缺省值 |
{%tr for row in rows %} | ||||||
{{row.xh}} | {{row.zdmc}} | {{row.zdms}} | {{row.zdlx}} | {{row.cd}} | {{row.yxk}} | {{row.qsz}} |
{%tr endfor %} |
模板下载连接:https://download.csdn.net/download/black_liu8561/11021767
以下是PY代码,代码写得稍微有点乱,现阶段是以实现为主,将就看,过段时间整理一下。
from docxtpl import DocxTemplate
import cx_Oracle
def create_word(data,templatepath,filepath,filename):
'''
根据模板创建docx文件的函数
:param data: docxtemplate模块所需字典,直接和docx文件进行关联
:param templatepath: docx模板路径
:param filepath: 保存的文件夹路径
:param filename: 保存的文件名
:return: 生成一个docx文件
'''
doc = DocxTemplate(templatepath)
context = data
savepath=filepath+filename+'.docx'
doc.render(context)
doc.save(savepath)
def create_docx(dbinfo,templatepath,filepath):
'''
读取数据库数据并封装成字典后传给create_word函数生成docx文件
:param dbinfo: 数据库信息
:return:
'''
connection = cx_Oracle.Connection(dbinfo)
cursor = connection.cursor()
sql='select * from ball where status=0'
cursor.execute(sql)
result=cursor.fetchone()
data={}
data['tablename']=result[0]
data['page']=result[3]
data['bzs']=result[2]
cursor.close()
#上述查询临时表数据
l=[]
cursor = connection.cursor()
sql1='''select rownum xh,t.COLUMN_NAME zdmc,t1.comments zdms,t.DATA_TYPE zdlx,t.DATA_LENGTH cd,t.NULLABLE,t.DATA_DEFAULT qsz from user_tab_cols t,user_col_comments t1
where t.COLUMN_NAME=t1.column_name(+) and
t.TABLE_NAME={0} and t1.table_name={1}'''.format("'"+data['tablename']+"'","'"+data['tablename']+"'")
cursor.execute(sql1)
result1=cursor.fetchall()
for i in result1:
row = {}
row['xh']=i[0]
row['zdmc'] = i[1]
row['zdms'] = i[2]
row['zdlx'] = i[3]
row['cd'] = i[4]
row['yxk'] = i[5]
row['qsz'] = i[6]
l.append(row)
data['rows']=l
create_word(data,templatepath=templatepath,filepath=filepath,filename=data['tablename'])
#创建文件
cursor = connection.cursor()
sql2 = '''update ball t set t.status=1 where t.table_name={0}'''.format("'"+data['tablename']+"'")
cursor.execute(sql2)
connection.commit()
cursor.close()
#修改状态
print(data['tablename']+'已生成')
dbinfo="username/passwd@localhost:1521/instance"
templatepath=r"C:\Users\Administrator\Desktop\test.docx"
filepath="C:\\Users\\Administrator\\Desktop\\"
#配置:数据库连接信息,docx模板位置,存储目录
while 1==1:
create_docx(dbinfo=dbinfo,templatepath=templatepath,filepath=filepath)