当前位置: 首页 > 后端技术 > Python

Python数据库格式化输出文档

时间:2023-03-26 00:06:11 Python

Question如果文案格式统一,doc/md文档可以通过Python格式化输出吗?如果可以用代码完成,尽量不要手动完成。首先,数据已经输入到数据库中。您需要使用python来读取数据库。您可以使用mysql连接器。其次,格式化后的输出文件必须需要文件读写操作,需要使用os.那么,考虑到各大平台大多支持markdown格式,先输出??md格式文档。如果要输出doc,需要使用docx来补充,python一键执行,分页数据操作,接收外部参数需要使用sys代码分页获取数据库内容importmysql.connector#中的分页数据数据库deffetch_data_from_db(page):cmd='select*fromxxxorderbyidlimit'+str(page*50)+','+str(50)conn=mysql.connector.connect(user='xxx',password='xxx',database='xxx')cursor=conn.cursor()cursor.execute(cmd)values=cursor.fetchall()conn.commit()cursor.close()conn.close()返回值格式化输出的md文档,在md中添加表格样式importos#python输出表格defexport_format_md(page,books):fileName='山寨书店号'+str(page)+'period.md'#追加文件fd=open(fileName,'a')fd.write('Bibliography:\n
\n\n')fd.write('|Index|Author|Title|\n')fd.write('|:-|:-|:-|\n')forbookinbooks:fd.write('|'+"{0:04d}".format(book[0])+'|'+book[2]+'|'+book[1]+'\n')格式然后输出docdocumentfromdocximportDocumentfromdocx.sharedimportCmdefexport_format_md(page,books):fileName='山寨书店'+str(page)+'period.docx'document=Document()table=document.add_table(rows=51,cols=3)#设置行数和列数table.cell(0,0).text="Index"table.cell(0,1).text="Author"table.cell(0,2).text="Booktitle"forindex,bookinenumerate(books):table.cell(index+1,0).text="{0:05d}".format(book[0])table.cell(index+1,1).text=book[2]table.cell(index+1,2).text=book[1]document.save(fileName)外参传递if__name__=='__main__':args=sys.argviflen(args)==2:#获取分页page=args[1]books=fetch_data_from_db(page)export_format_md(page,books)一键执行python3xxxx.py0Over

猜你喜欢