本文實例講述了python實現的生成word文檔功能。分享給大家供大家參考,具體如下:
每月1次的測試費用報銷,需要做一個文檔。干脆花點時間寫個程序吧。
# -*- coding: utf-8 -*-
from tools import get_data
from docx import Document
def new_doc(fee_data,doc_path,fee):#新建一個word文檔,寫入匯總表的數據
document = Document()
p_total = document.add_paragraph()
r_total = p_total.add_run(u'測試訂單費用匯總表:')
r_total.font.bold = True
table = document.add_table(1,5,)
heading_cells = table.rows[0].cells
heading_cells[0].text = u'序號'
heading_cells[1].text = u'訂單號'
heading_cells[2].text = u'訂單總額'
heading_cells[3].text = u'運費'
heading_cells[4].text = u'實付金額'
total = 0
for i in range(0,len(fee_data)):
cells = table.add_row().cells
cells[0].text = str(i+1)
cells[1].text = str(fee_data[i][0])
cells[2].text = str(float(fee_data[i][1])/100)
cells[3].text = str(float(fee_data[i][2])/100)
cells[4].text = str(float(fee_data[i][3])/100)
total = total + fee_data[i][3]
if total > fee:#如果實付總額大于傳入的金額,終止寫入數據,并記錄序號
number = i
break
total = str(float(total)/100)
document.add_paragraph(u'實付金額總計:' + total + u' 元。')
document.add_paragraph()
p_detail = document.add_paragraph()
r_detail = p_detail.add_run(u'測試訂單明細:')
r_detail.font.bold = True
for i in range(0,number+1):
order_no = str(fee_data[i][0])
paid_amount = str(float(fee_data[i][3])/100)
row_str = str(i+1) + '.' + u'訂單號:' + order_no + u'實付金額:' + paid_amount + u'元。'
document.add_paragraph(row_str)
document.save(doc_path)
if __name__ == "__main__":
#sql語句篩選實付金額在5元和39元之間的訂單
sql = "SELECT outer_order_id,order_amount,real_shipping_amount,paid_amount FROM oh_order_info WHERE " \
"order_create_time between '2017-12-01 9:00:00' and '2017-12-27 9:00:00' " \
"AND paid_amount between '500' and '3900'"
fee_data = get_data(sql)
doc_path = r'd:\yuzhong.docx'
fee = 12300 #多少元以上,單位:分
new_doc(fee_data,doc_path,fee)
使用到的tools文件中get_data函數
# -*- coding: utf-8 -*- import MySQLdb import conf def get_data(*sql_list):#根據sql語句,獲取數據庫的數據 conn = MySQLdb.connect(conf.test_dbhost,conf.test_user,conf.test_passd,conf.test_dbname,port=3306,charset="utf8") cur = conn.cursor() for sql in sql_list: cur.execute(sql) conn.commit() results = cur.fetchall() cur.close() conn.close() return results
conf文件中記錄的數據庫帳號和密碼。
運行結果:

更多關于Python相關內容感興趣的讀者可查看本站專題:《Python數據結構與算法教程》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》、《Python入門與進階經典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。