Thoughts and Methods of Formatting Output Documents in Python Database
- 2021-09-20 21:11:41
- OfStack
Problem
If the copy format is Uniform 1, can doc/md documents be output through Python formatting?
Can be done with code, try not to manually
Train of thought
First of all, the data has been entered into the database, and python is required to read the database. mysql-connector can be used
Secondly, formatting the output document definitely requires file reading and writing operations, and needs to use os
Then, considering that most platforms support markdown format, md format documents are preferentially output. If doc is output, docx is required
Supplementary, python1 key execution, paging data operation, receiving external parameters, sys is required
Code
Paging to get database content
import mysql.connector
# In the database page Page data
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
Format output md document, add table style in md
import mysql.connector
# In the database page Page data
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
Output doc document in format
from docx import Document
from docx.shared import Cm
def export_format_md(page, books):
fileName = ' Shan Zhai Bookstore No.1 ' + str(page) + ' Period .docx'
document = Document()
table = document.add_table(rows = 51, cols = 3) # Set the number of rows and columns
table.cell(0, 0).text = " Index "
table.cell(0, 1).text = " Author "
table.cell(0, 2).text = " Book title "
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)
External parameter acquisition
if __name__ == '__main__':
args = sys.argv
if len(args) == 2:
# Get paging
page = args[1]
books = fetch_data_from_db(page)
export_format_md(page, books)
1 key execution
python3 xxxx.py 0