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,style="Light List Accent 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文件中記錄的數據庫帳號和密碼。
運行結果:
這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章