Ideas and methods of formatting output documents in Python database

Time:2021-10-26

problem

If the document format is uniform, can I format and output Doc / MD documents through Python?

It can be done in code. Try not to do it manually

thinking

First of all, the data has been recorded into the database. You need Python to be able to read the database. You can use MySQL connector

Secondly, to format the output document, you must use OS to read and write the file

Then, considering that most major platforms support markdown format, give priority to outputting MD format documents. To output doc, you need to use docx

In addition, python needs to use sys for one click execution, paging data operation and receiving external parameters

code

Get database contents by paging

?
1
2
3
4
5
6
7
8
9
10
11
12
13
import mysql.connector
 
#Page data in database
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 the output MD document and add table styles to MD

?
1
2
3
4
5
6
7
8
9
10
11
12
13
import mysql.connector
 
#Page data in database
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 document output format

?
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 = 'shanzhai Bookstore No + str(page) + 'issue. 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 = "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

?
1
2
3
4
5
6
7
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)

One click execution

?
1
python3 xxxx.py 0

summary

This is the end of this article on Python database formatting output documents. For more information about Python database formatting output, please search for previous articles on developeppaper or continue to browse the relevant articles below. I hope you will support developeppaper in the future!