本文實例講述了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文件中記錄的數據庫帳號和密碼。
運行結果:
更多關于Python相關內容感興趣的讀者可查看本站專題:《Python數據結構與算法教程》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》、《Python入門與進階經典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
