脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python数据库格式化输出文档的思路与方法

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

2021-09-18 00:17善斋书屋 Python

这篇文章主要给大家介绍了关于Python数据库格式化输出文档的思路与方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

问题

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

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

思路

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

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

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

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

编码

分页获取数据库内容

?
1
2
3
4
5
6
7
8
9
10
11
12
13
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中添加表格样式

?
1
2
3
4
5
6
7
8
9
10
11
12
13
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文档

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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)

外部传参获取

?
1
2
3
4
5
6
7
if __name__ == '__main__':
 args = sys.argv
 if len(args) == 2:
  # 获取分页
  page = args[1]
  books = fetch_data_from_db(page)
  export_format_md(page, books)

一键执行

?
1
python3 xxxx.py 0

总结

到此这篇关于Python数据库格式化输出文档的文章就介绍到这了,更多相关Python数据库格式化输出内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://segmentfault.com/a/1190000039343618

延伸 · 阅读

精彩推荐