主頁(yè) > 知識(shí)庫(kù) > Python數(shù)據(jù)庫(kù)格式化輸出文檔的思路與方法

Python數(shù)據(jù)庫(kù)格式化輸出文檔的思路與方法

熱門標(biāo)簽:客戶服務(wù) 電話運(yùn)營(yíng)中心 企業(yè)做大做強(qiáng) 語(yǔ)音系統(tǒng) Win7旗艦版 百度AI接口 硅谷的囚徒呼叫中心 呼叫中心市場(chǎng)需求

問(wèn)題

如果文案格式是統(tǒng)一的,是否可以通過(guò)Python格式化輸出doc/md的文檔?

能用代碼搞定的,盡力不手工

思路

首先,數(shù)據(jù)已經(jīng)錄入庫(kù),需要python能讀取數(shù)據(jù)庫(kù),可使用mysql-connector

其次,格式化輸出的文檔,肯定需要文件讀寫操作,需使用os

接著,考慮到各大平臺(tái)多數(shù)支持markdown格式,優(yōu)先輸出md格式文檔。若輸出doc,需使用docx

補(bǔ)充,python一鍵執(zhí)行,分頁(yè)數(shù)據(jù)操作,接收外部參數(shù),需使用sys

編碼

分頁(yè)獲取數(shù)據(jù)庫(kù)內(nèi)容

import mysql.connector

# 數(shù)據(jù)庫(kù)中page頁(yè)數(shù)據(jù)
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

# 數(shù)據(jù)庫(kù)中page頁(yè)數(shù)據(jù)
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) # 設(shè)置行列數(shù)
 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:
  # 獲取分頁(yè)
  page = args[1] 
  books = fetch_data_from_db(page)
  export_format_md(page, books)

一鍵執(zhí)行

python3 xxxx.py 0

總結(jié)

到此這篇關(guān)于Python數(shù)據(jù)庫(kù)格式化輸出文檔的文章就介紹到這了,更多相關(guān)Python數(shù)據(jù)庫(kù)格式化輸出內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

您可能感興趣的文章:
  • python中日期和時(shí)間格式化輸出的方法小結(jié)
  • python中的格式化輸出用法總結(jié)
  • Python中使用pprint函數(shù)進(jìn)行格式化輸出的教程
  • python格式化輸出保留2位小數(shù)的實(shí)現(xiàn)方法
  • Python實(shí)現(xiàn)小數(shù)轉(zhuǎn)化為百分?jǐn)?shù)的格式化輸出方法示例
  • 在python中用print()輸出多個(gè)格式化參數(shù)的方法
  • python常見的格式化輸出小結(jié)
  • Python格式化輸出%s和%d

標(biāo)簽:長(zhǎng)沙 山西 海南 崇左 安康 濟(jì)南 山西 喀什

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Python數(shù)據(jù)庫(kù)格式化輸出文檔的思路與方法》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266