SoFunction
Updated on 2024-11-18

Python database formatting output document ideas and methods

concern

If the copy format is uniform, is it possible to format the output doc/md document via Python?

If you can do it in code, try not to do it by hand.

reasoning

First, the data has been entered into the database, need python can read the database, you can use mysql-connector

Second, formatting the output document, certainly need to read and write the file operation, need to use os

Next, considering that most of the major platforms support markdown format, the priority is to output documents in md format. If you want to output doc, you need to use docx.

Supplementary, python one-click execution, paging data manipulation, receiving external parameters, need to use sys

encodings

Paging for database content

import 

# page page data in the database
def fetch_data_from_db(page):
 cmd = 'select * from xxx order by id limit ' + str(page * 50) + ', ' + str(50)
 conn = (user='xxx', password='xxx', database='xxx')
 cursor = ()
 (cmd)
 values = ()
 ()
 ()
 () 
 return values 

Formatting output md documents, adding table styles in md

import 

# page page data in the database
def fetch_data_from_db(page):
 cmd = 'select * from xxx order by id limit ' + str(page * 50) + ', ' + str(50)
 conn = (user='xxx', password='xxx', database='xxx')
 cursor = ()
 (cmd)
 values = ()
 ()
 ()
 () 
 return values 

Formatting words to output doc files

from docx import Document
from  import Cm

def export_format_md(page, books):
 fileName = 'Shansai Shuji No. 1' + str(page) + 'Period.docx'
 document = Document()
 table = document.add_table(rows = 51, cols = 3) # of rows and columns set
 (0, 0).text = "Index."
 (0, 1).text = "Author."
 (0, 2).text = "Title of the book."
 for index, book in enumerate(books):
  (index+1, 0).text = "{0:05d}".format(book[0])
  (index+1, 1).text = book[2]
  (index+1, 2).text = book[1]
 (fileName)

Get external parameter passing

if __name__ == '__main__':
 args = 
 if len(args) == 2:
  # Get Pagination
  page = args[1] 
  books = fetch_data_from_db(page)
  export_format_md(page, books)

one-click execution

python3  0

summarize

to this article on the Python database formatting output document is introduced to this article, more related Python database formatting output content, please search for my previous articles or continue to browse the following related articles I hope you will support me in the future more!