Python3使用docx生成word报告

from docx import Document
from docx.shared import Inches,Pt
from docx.oxml.ns import qn 
import pymysql
from docx.enum.text import * 
from docx.shared import Length
import requests
import json
from TrainNumHelper import *
from CreateChart import *
from SignallingAnalysis import SignallingAnalysis
from SignallingDisplay import SignallingDisplay
import sqlite3
import copy
import datetime
import time
import os


class CreateReportService() :

    def chg_font(self,obj,fontname='微软雅黑',size = None):
    ## 设置字体函数
        obj.font.name = fontname
        obj._element.rPr.rFonts.set(qn('w:eastAsia'),fontname)
        #if size and isinstance(size,Pt):
        obj.font.size = size
    
    def createReport(self,row):
        id = row[0] 
        cheCiHao = row[2] 
        lastTrainNum = int(cheCiHao[-1]) % 2 
        shangOrXia = "上" if lastTrainNum == 0  else "下"  
        guZhangShiJian = row[8].strftime("%Y-%m-%d %H:%M:%S")  
        huiFuShiJian = row[12].strftime("%Y-%m-%d %H:%M:%S") 
        MT1 = row[6]  
        MT2 = row[11]  
        prePriId = row[4]  
        curPriId = row[9]  
        preSetupTime = row[7].strftime("%Y-%m-%d %H:%M:%S")  
        curSetupTime = row[12].strftime("%Y-%m-%d %H:%M:%S")  
        preDiscTime = row[8].strftime("%Y-%m-%d %H:%M:%S")  
        curDiscTime = row[13].strftime("%Y-%m-%d %H:%M:%S")  
        
        data12 = {
           "id" : id,
           "divId" : "chart12",
           "cheCiHao" : cheCiHao,
           "MT1" : MT1,
           "MT2" : MT2,
           "prePriId" : prePriId,
           "curPriId" : curPriId,
           "preSetupTime" : preSetupTime,
           "curSetupTime" : curSetupTime,
           "preDiscTime" : preDiscTime,
           "curDiscTime" : curDiscTime
        }
        data34={
           "id" : id,
           "divId" : "chart34",
           "cheCiHao" : cheCiHao,
           "MT1" : MT1,
           "MT2" : MT2,
           "prePriId" : prePriId,
           "curPriId" : curPriId,
           "preSetupTime" : preSetupTime,
           "curSetupTime" : curSetupTime,
           "preDiscTime" : preDiscTime,
           "curDiscTime" : curDiscTime
        }
        post_headers = {'Content-Type':'application/json',"Accept": "*/*"}
        result12 = requests.post('http://localhost:8888/createChart', data = json.dumps(data12),headers=post_headers)
        print(result12.text)
        chart12_path = result12.text
        
        result34 = requests.post('http://localhost:8888/createChart', data = json.dumps(data34),headers=post_headers)
        print(result34.text)
        chart34_path = result34.text
        
        root = os.path.dirname(__file__)+"//sqlite"
        pre = f"{id}_{cheCiHao}_{prePriId}_pre.db"
        cur = f"{id}_{cheCiHao}_{curPriId}_cur.db"
        #数据分析
        signalling_analysis = SignallingAnalysis(root, pre, root, cur)
        data_analysis = signalling_analysis.start()
        ctcs_id_pre = data_analysis["conclusion_other"]["ctcs_id_pre"]
        type = data_analysis["conclusion_other"]["type"]  #故障类型
        print(data_analysis)
        #信令分析
        signalling_display = SignallingDisplay(root, pre, root, cur)
        data_display = signalling_display.start()
        print(data_display)
        
        doc = Document()  
        distance = Inches(0.7)   #英寸
        top_distance = Inches(1)   
        sec = doc.sections[0]          # sections对应文档中的“节”
        
        header = sec.header
        header_paragraph = header.add_paragraph()
        header_run = header_paragraph.add_run("")
        header_run.add_picture(os.path.dirname(__file__)+"\\common\\logo.png",width=Inches(2.7))  

        sec.header_distance = Inches(0.1)
        sec.left_margin = distance     # 以下依次设置左、右、上、下页面边距 
        sec.right_margin = distance
        sec.top_margin = top_distance
        sec.bottom_margin = distance
         
        sec.page_width =Inches(8.27)        #设置页面宽度A4标准
        sec.page_height = Inches(11.69)       #设置页面高度 
        
        paragraph1 =doc.add_paragraph()  
        run1 = paragraph1.add_run(cheCiHao + '嘻嘻嘻嘻嘻嘻嘻嘻寻')
        run1.bold = True
        self.chg_font(self,run1,fontname='黑体', size=Pt(25))  #设置字体和字号
        
        paragraph1.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
        #paragraph1.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
        paragraph2 =doc.add_paragraph()

        ph_format =paragraph2.paragraph_format
        ph_format.space_before =Pt(10)      #设置段前间距 
        ph_format.space_after =Pt(12)       #设置段后间距
        ph_format.line_spacing=Pt(25)       #设置行间距
      
        run = paragraph2.add_run('一、    xx现象')
        run.bold = False #设置字体为粗体
        self.chg_font(self,run,fontname='仿宋', size=Pt(20))  #设置字体和字号
      
        paragraph3 =doc.add_paragraph()
        run = paragraph3.add_run(f"    {guZhangShiJian},{cheCiHao}次列车{shangOrXia}嘻嘻嘻嘻嘻嘻嘻嘻寻寻寻,{huiFuShiJian}嘻嘻嘻嘻嘻嘻嘻嘻。")
        run.bold = False 
        self.chg_font(self,run,fontname='宋体', size=Pt(14))  #设置字体和字号
        paragraph4 =doc.add_paragraph()
        run = paragraph4.add_run(f"    嘻嘻嘻嘻嘻嘻嘻嘻寻寻寻")
        self.chg_font(self,run,fontname='宋体', size=Pt(14))  #设置字体和字号
        if len(chart12_path) != 0 and len(chart34_path) != 0 : 
            paragraph5 =doc.add_paragraph()
            run = paragraph5.add_run(f"    嘻嘻嘻嘻嘻嘻嘻嘻,{cheCiHao}次车载占用{ctcs_id_pre}休息休息。\n" + "    嘻嘻嘻嘻嘻嘻:\n" + "    时间分布")
            self.chg_font(self,run,fontname='宋体', size=Pt(14))  #设置字体和字号
            paragraph6 =doc.add_paragraph()
            paragraph6.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
            run = paragraph6.add_run("")
            run.add_picture(chart12_path,width=Inches(7))  
            paragraph7 =doc.add_paragraph()
            run = paragraph7.add_run("    嘻嘻嘻嘻嘻")
            self.chg_font(self,run,fontname='宋体', size=Pt(14))  #设置字体和字号
            paragraph8 =doc.add_paragraph()
            paragraph8.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
            run = paragraph8.add_run("")
            run.add_picture(chart34_path,width=Inches(7))  
        paragraph9 =doc.add_paragraph()
        run = paragraph11.add_run("三、    嘻嘻嘻嘻嘻")
        self.chg_font(self,run,fontname='仿宋', size=Pt(20))  #设置字体和字号
        
        paragraph12 =doc.add_paragraph()
        run = paragraph12.add_run("1.    嘻嘻嘻嘻嘻嘻嘻")
        self.chg_font(self,run,fontname='仿宋', size=Pt(17))  #设置字体和字号
        doc.styles['Normal'].font.size = Pt(10)   # 修改全局默认的格式
        
        if len(data_display["data_pri_pre"]) != 0 : 
            paragraph11 =doc.add_paragraph()
            run = paragraph11.add_run(f"MT1({MT1}):")
            self.chg_font(self,run,fontname='黑体', size=Pt(14))  #设置字体和字号
            tab =doc.add_table(rows=len(data_display["data_pri_pre"]) + 1,cols=5,style='Table Grid')   #添加一个4行4列的空表
            tab.cell(0,0).text = "时间"  
            tab.cell(0,1).text = "呼叫方向"  
            tab.cell(0,2).text = "公里标"  
            tab.cell(0,3).text = "msgtype"  
            tab.cell(0,4).text = "subtype"  
            for i in range(1,len(data_display["data_pri_pre"]) + 1):
                tab.cell(i,0).text = data_display["data_pri_pre"][i-1]["msgtimestamp"]  
                tab.cell(i,1).text = data_display["data_pri_pre"][i-1]["direction"]  
                tab.cell(i,2).text = data_display["data_pri_pre"][i-1]["kmpost"]  
                tab.cell(i,3).text = data_display["data_pri_pre"][i-1]["msgtype"]  
                tab.cell(i,4).text = data_display["data_pri_pre"][i-1]["subtype"] 
        paragraph14 =doc.add_paragraph()
        run = paragraph14.add_run("4.    根深蒂固电饭锅电饭锅")
        self.chg_font(self,run,fontname='仿宋', size=Pt(17))  #设置字体和字号
        
        if len(data_analysis["data_abis_pre"]) != 0 : 
            paragraph11 =doc.add_paragraph()
            run = paragraph11.add_run(f"MT1({MT1}):")
            self.chg_font(self,run,fontname='黑体', size=Pt(14))  #设置字体和字号
            tab =doc.add_table(rows=len(data_analysis["data_abis_pre"]) + 1,cols=5,style='Table Grid')   #添加一个4行4列的空表
            tab.cell(0,0).text = "时间"  
            tab.cell(0,1).text = "呼叫方向"  
            tab.cell(0,2).text = "公里标"  
            tab.cell(0,3).text = "msgtype"  
            tab.cell(0,4).text = "subtype"  
            for i in range(1,len(data_analysis["data_abis_pre"]) + 1):
                tab.cell(i,0).text = data_analysis["data_abis_pre"][i-1]["msgtimestamp"]   
                tab.cell(i,1).text = data_analysis["data_abis_pre"][i-1]["direction"]  
                tab.cell(i,2).text = data_analysis["data_abis_pre"][i-1]["kmpost"]  
                tab.cell(i,3).text = data_analysis["data_abis_pre"][i-1]["msgtype"]  
                tab.cell(i,4).text = data_analysis["data_abis_pre"][i-1]["subtype"] 
       
        paragraph12 =doc.add_paragraph()
        run = paragraph12.add_run("5.    把把把把把把把把把把把")
        self.chg_font(self,run,fontname='仿宋', size=Pt(17))  #设置字体和字号
        
        if len(data_display["data_a_pre"]) != 0 : 
            paragraph11 =doc.add_paragraph()
            run = paragraph11.add_run(f"MT1({MT1}):")
            self.chg_font(self,run,fontname='黑体', size=Pt(14))  #设置字体和字号
            tab =doc.add_table(rows=len(data_display["data_a_pre"]) + 1,cols=5,style='Table Grid')   #添加一个4行4列的空表
            tab.cell(0,0).text = "时间"  
            tab.cell(0,1).text = "呼叫方向"  
            tab.cell(0,2).text = "公里标"  
            tab.cell(0,3).text = "msgtype"  
            tab.cell(0,4).text = "subtype"  
            for i in range(1,len(data_display["data_a_pre"]) + 1):
                tab.cell(i,0).text = data_display["data_a_pre"][i-1]["msgtimestamp"]  
                tab.cell(i,1).text = data_display["data_a_pre"][i-1]["direction"]  
                tab.cell(i,2).text = data_display["data_a_pre"][i-1]["kmpost"]  
                tab.cell(i,3).text = data_display["data_a_pre"][i-1]["msgtype"]  
                tab.cell(i,4).text = data_display["data_a_pre"][i-1]["subtype"] 
        if len(data_display["data_a_cur"]) != 0 : 
            paragraph11 =doc.add_paragraph()
            run = paragraph11.add_run(f"MT2({MT2}):")
            self.chg_font(self,run,fontname='黑体', size=Pt(14))  #设置字体和字号
            tab =doc.add_table(rows=len(data_display["data_a_cur"]) + 1,cols=5,style='Table Grid')   #添加一个4行4列的空表
            tab.cell(0,0).text = "时间"  
            tab.cell(0,1).text = "呼叫方向"  
            tab.cell(0,2).text = "公里标"  
            tab.cell(0,3).text = "msgtype"  
            tab.cell(0,4).text = "subtype"  
            for i in range(1,len(data_display["data_a_cur"]) + 1):
                tab.cell(i,0).text = data_display["data_a_cur"][i-1]["msgtimestamp"]  
                tab.cell(i,1).text = data_display["data_a_cur"][i-1]["direction"]  
                tab.cell(i,2).text = data_display["data_a_cur"][i-1]["kmpost"]  
                tab.cell(i,3).text = data_display["data_a_cur"][i-1]["msgtype"]  
                tab.cell(i,4).text = data_display["data_a_cur"][i-1]["subtype"]
        
        paragraph14 =doc.add_paragraph()
        run = paragraph14.add_run("6.    嘻嘻嘻嘻嘻嘻嘻嘻")
        self.chg_font(self,run,fontname='仿宋', size=Pt(17))  #设置字体和字号
        
        run = paragraph9.add_run("四、 反复反复付付付付")
        self.chg_font(self,run,fontname='仿宋', size=Pt(20))  #设置字体和字号
        paragraph11 =doc.add_paragraph()
        run = paragraph11.add_run("     反复反复付付付付付所所所所。")
        self.chg_font(self,run,fontname='仿宋', size=Pt(14))  #设置字体和字号
        
        doc.save(f'{cheCiHao}_{id}.docx') 
        print(f"生成报告成功-------->{cheCiHao}_{id}.docx")
        

你可能感兴趣的:(Python3使用docx生成word报告)