Python数据库格式化输出 Python数据库格式化输出文档的思路与方法

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Python数据库格式化输出 Python数据库格式化输出文档的思路与方法

善斋书屋   2021-03-15 我要评论
想了解Python数据库格式化输出文档的思路与方法的相关内容吗,善斋书屋在本文为您仔细讲解Python数据库格式化输出的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:python格式化输出,python和数据库,Python,格式化,下面大家一起来学习吧。

问题

如果文案格式是统一的,是否可以通过Python格式化输出doc/md的文档?

能用代码搞定的,尽力不手工

思路

首先,数据已经录入库,需要python能读取数据库,可使用mysql-connector

其次,格式化输出的文档,肯定需要文件读写操作,需使用os

接着,考虑到各大平台多数支持markdown格式,优先输出md格式文档。若输出doc,需使用docx

补充,python一键执行,分页数据操作,接收外部参数,需使用sys

编码

分页获取数据库内容

import mysql.connector

# 数据库中page页数据
def fetch_data_from_db(page):
 cmd = 'select * from xxx order by id limit ' + 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() 
 return values 

格式化输出md文档,md中添加表格样式

import mysql.connector

# 数据库中page页数据
def fetch_data_from_db(page):
 cmd = 'select * from xxx order by id limit ' + 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() 
 return values 

格式话输出doc文档

from docx import Document
from docx.shared import Cm

def export_format_md(page, books):
 fileName = '善斋书屋第' + str(page) + '期.docx'
 document = Document()
 table = document.add_table(rows = 51, cols = 3) # 设置行列数
 table.cell(0, 0).text = "索引"
 table.cell(0, 1).text = "作者"
 table.cell(0, 2).text = "书名"
 for index, book in enumerate(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.argv
 if len(args) == 2:
  # 获取分页
  page = args[1] 
  books = fetch_data_from_db(page)
  export_format_md(page, books)

一键执行

python3 xxxx.py 0

总结

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们