python处理word

#coding:utf-8   #是用来指定文件编码为utf-8的
import os
import codecs#涉及到文件目录有中文日文英文,其ASCII格式不一样


from tkinter import *
from tkinter import messagebox   #导入tkMessageBox
from tkinter.filedialog import askdirectory     #返回文件夹路径,不是文件路径使用
import tkinter.filedialog
import tkinter.messagebox
from tkinter import ttk
import re 
import time #定时使用


#以下是将docx文件转为doc文件实用。需要调用office中的API
import win32com
from win32com.client import Dispatch
import shutil


from PIL import Image,ImageTk


#调试用
import traceback 


#定义列表,用于检索详细设计书中每个章节的位置
LST_1 = ['HEAD1']
LST_2 = ['HEAD2']
st = ''
#分别为第1,2,3,4,5,6章节头和为行号
#                  1             2           3                   4               5               6              7'预留用'        Head         No           SYD
LINE_NUM = [['NULL','NULL'],['NULL','NULL'],['NULL','NULL'],['NULL','NULL'],['NULL','NULL'],['NULL','NULL'],['NULL','NULL'],['NULL','NULL'],['NULL','NULL'],['NULL','NULL']]


#获取的第一个表
Head_Tab = 0
head_tab_falg = True


def readCfgFile1_1():
    global LST_1
    f = open(r'.\cfg\Set_pattern.cfg')
    ls1 = []
    ls1_1 = []
    ReGetHead = re.compile('[0-9]*\.1')#找到1.1章节
    for line in f:
        ls1 = ReGetHead.findall(line)
        #print('ls1=',end = '')
        st = ''.join(ls1)  #将列表转为字符串,该列表只有一个成员。转换为字符串后可以计算长度
        #print(''.join(ls1))
        #print('len=',end = '')
        #print(len(st))
        if ls1 != []:  #从cfg文件读到内容,经过匹配后不为空
            if len(st) == 3:#由于1.1和10.1的长度不一样
                ls1_1 = line[3:len(line)-1].split(" ") #将字符串转为列表
                #print(ls1_1)
            if len(st) == 4:
                ls1_1 = line[4:len(line)-1].split(" ") #将字符串转为列表
                #print(ls1_1)
            
            LST_1=LST_1+ ls1_1
    #print('LST_1 = ',end = '')
    #print(LST_1)
   
    f.close()


def readCfgFile1_2():
    global LST_2
    f = open(r'.\cfg\Set_pattern.cfg')
    ls1 = []
    ls1_1 = []
    ReGetHead = re.compile('[0-9]*\.2')#找到1.1章节
    for line in f:
        ls1 = ReGetHead.findall(line)
        st = ''.join(ls1)
        if ls1 != []:  #从cfg文件读到内容,经过匹配后不为空
            if len(st) == 3:
                ls1_1 = line[3:len(line)-1].split(" ") #将字符串转为列表
                #print(ls1_1)
            if len(st) == 4:
                ls1_1 = line[4:len(line)-1].split(" ") #将字符串转为列表
                #print(ls1_1)
            
            LST_2=LST_2+ ls1_1
    #print('LST_2 = ',end = '')
    #print(LST_2)        
    f.close()


    


class Application(Frame):
    filename = ''
    WordApp =''
    doc = ''
    sel=''




    def __init__(self,master = None):
        Frame.__init__(self,master)
        self.grid(row = 0,column = 5)
        self.path2 = StringVar()#先在此处定义,在函数selectDocx()被调用时赋值
        self.createWidgets()
        
        
    def createWidgets(self):
        #docx路径选择标签
        self.DocxPathLabel = Label(self,text = "docx路径:", bg = '#f0fff0',height = 1,width = 7)
        self.DocxPathLabel.grid(row = 0, column = 0,pady = 5,sticky=N+S+W+E)  #sticky=N+S上下对齐


        #entry内容设置
        self.DocxPathEntry = Entry(self, textvariable = self.path2,width = 50,bg = '#f0fff0',selectbackground  = 'red') #entry 的text属性不可以设置文本格式,在Entry中设定初始值,使用textvariable将变量与Entry绑定
        self.DocxPathEntry.grid(row = 0, column = 1,pady = 5,sticky=N+S)#padx=2,与前一个控件水平距离
        self.DocxPathEntry.insert(0,'点击<docx选择>按键,显示所选docx文件路径……')
        #docx选择按钮设置
        self.ProButton = Button(self, text = "docx选择", bg = '#fff8dc',height = 1,width = 7,command = self.selectDocx)
        self.ProButton.grid(row = 0, column = 2,pady = 5,sticky=N+S)


        
        #画图框架图1
        self.canvas1 = Canvas(self, width = 200, height = 200, bg = "#f0fff0")
        #self.canvas.create_rectangle(5,10,460,100,outline = 'red',dash = 10,fill = '#fff8dc')
        load1 = Image.open(r".\cfg\python_1")
        #print(load1.format,int(load1.size[0]/3*2),int(load1.size[1]/3*2),load1.mode)
        render1 = ImageTk.PhotoImage(load1)
        #img1 = load1.resize((456, 210),Image.ANTIALIAS)
        img1 = load1.resize((int(load1.size[0]/3*2),int(load1.size[1]/3*2)),Image.ANTIALIAS)
        render1 = ImageTk.PhotoImage(img1)
        self.canvas1.image =render1  #这里会让图片显示出来
        self.canvas1.create_image(232,100,image = render1)  #中心位置
        self.canvas1.grid(row = 1, column = 0,columnspan=3,sticky=W+E)
        #myText=self.canvas.create_text(100,50,text='SheMingLi')
        




        #"""
        #画图框架图2
        self.canvas2 = Canvas(self, width = 200, height = 60, bg = "#f0fff0")
        #self.canvas2.create_rectangle(5,10,460,100,outline = 'red',dash = 10,fill = '#fff8dc')
        load2 = Image.open(r".\cfg\python_2")
        #print(load2.format,int(load2.size[0]/3*2),int(load2.size[1]/3*2),load2.mode)
        render2 = ImageTk.PhotoImage(load2)
        #img2 = load2.resize((457, 438),Image.ANTIALIAS)#457,438
        img2 = load2.resize((int(load2.size[0]/3*2),int(load2.size[1]/3*2)),Image.ANTIALIAS)
        render2 = ImageTk.PhotoImage(img2)
        self.canvas2.image =render2  #这里会让图片显示出来
        self.canvas2.create_image(232,30,image = render2)  #中心位置W232,H320
        self.canvas2.grid(row = 2, column = 0,columnspan=3,sticky=W+E)
        #myText=self.canvas2.create_text(100,500,text='SheMingLi')
        #"""


        #画图框架图3
        self.canvas3 = Canvas(self, width = 200, height = 50, bg = "#f0fff0")
        #self.canvas3.create_rectangle(5,10,460,100,outline = 'red',dash = 10,fill = '#fff8dc')
        load3 = Image.open(r".\cfg\python_3")
        #print(load3.format,int(load3.size[0]/3*2),int(load3.size[1]/3*2),load3.mode)
        render3 = ImageTk.PhotoImage(load3)
        #img3 = load3.resize((456, 210),Image.ANTIALIAS)
        img3 = load3.resize((int(load3.size[0]/3*2),int(load3.size[1]/3*2)),Image.ANTIALIAS)
        render3 = ImageTk.PhotoImage(img3)
        self.canvas3.image =render3  #?—¢‰ï??•Ð?Ž¦o—ˆ
        self.canvas3.create_image(372,27,image = render3)  
        self.canvas3.grid(row = 3, column = 0,columnspan=3,sticky=W+E)
        #myText=self.canvas3.create_text(100,50,text='SheMingLi')
    
        #画图框架图4
        self.canvas4 = Canvas(self, width = 200, height = 46, bg = "#f0fff0")
        #self.canvas4.create_rectangle(5,10,460,100,outline = 'red',dash = 10,fill = '#fff8dc')
        load4 = Image.open(r".\cfg\python_4")
        #print(load4.format,int(load4.size[0]/3*2),int(load4.size[1]/3*2),load4.mode)
        render4 = ImageTk.PhotoImage(load4)
        #img4 = load4.resize((456, 210),Image.ANTIALIAS)
        img4 = load4.resize((int(load4.size[0]/3*2),int(load4.size[1]/3*2)),Image.ANTIALIAS)
        render4 = ImageTk.PhotoImage(img4)
        self.canvas4.image =render4  #?—¢‰ï??•Ð?Ž¦o—ˆ
        self.canvas4.create_image(232,25,image = render4)  
        self.canvas4.grid(row = 4, column = 0,columnspan=3,sticky=W+E)
        #myText=self.canvas4.create_text(100,50,text='SheMingLi')


        #画图框架图5
        self.canvas5 = Canvas(self, width = 200, height = 70, bg = "#f0fff0")
        #self.canvas5.create_rectangle(5,10,460,100,outline = 'red',dash = 10,fill = '#fff8dc')
        load5 = Image.open(r".\cfg\python_5")
        #print(load5.format,int(load5.size[0]/3*2),int(load5.size[1]/3*2),load5.mode)
        render5 = ImageTk.PhotoImage(load5)
        #img5 = load5.resize((456, 210),Image.ANTIALIAS)
        img5 = load5.resize((int(load5.size[0]/3*2),int(load5.size[1]/3*2)),Image.ANTIALIAS)
        render5 = ImageTk.PhotoImage(img5)
        self.canvas5.image =render5  #?—¢‰ï??•Ð?Ž¦o—ˆ
        self.canvas5.create_image(232,38,image = render5)  
        self.canvas5.grid(row = 5, column = 0,columnspan=3,sticky=W+E)
        #myText=self.canvas5.create_text(100,50,text='SheMingLi')


        #画图框架图6
        self.canvas6 = Canvas(self, width = 200, height = 70, bg = "#f0fff0")
        #self.canvas6.create_rectangle(5,10,460,100,outline = 'red',dash = 10,fill = '#fff8dc')
        load6 = Image.open(r".\cfg\python_6")
        #print(load6.format,int(load6.size[0]/3*2),int(load6.size[1]/3*2),load6.mode)
        render6 = ImageTk.PhotoImage(load6)
        #img6 = load6.resize((456, 210),Image.ANTIALIAS)
        img6 = load6.resize((int(load6.size[0]/3*2),int(load6.size[1]/3*2)),Image.ANTIALIAS)
        render6 = ImageTk.PhotoImage(img6)
        self.canvas6.image =render6  #?—¢‰ï??•Ð?Ž¦o—ˆ
        self.canvas6.create_image(232,38,image = render6)  
        self.canvas6.grid(row = 6, column = 0,columnspan=3,sticky=W+E)
        #myText=self.canvas6.create_text(100,50,text='SheMingLi')


        #画图框架图7
        self.canvas7 = Canvas(self, width = 200, height = 46, bg = "#f0fff0")
        #self.canvas7.create_rectangle(5,10,460,100,outline = 'red',dash = 10,fill = '#fff8dc')
        load7 = Image.open(r".\cfg\python_7")
        #print(load7.format,int(load7.size[0]/3*2),int(load7.size[1]/3*2),load7.mode)
        render7 = ImageTk.PhotoImage(load7)
        #img7 = load7.resize((456, 210),Image.ANTIALIAS)
        img7 = load7.resize((int(load7.size[0]/3*2),int(load7.size[1]/3*2)),Image.ANTIALIAS)
        render7 = ImageTk.PhotoImage(img7)
        self.canvas7.image =render7  #?—¢‰ï??•Ð?Ž¦o—ˆ
        self.canvas7.create_image(232,25,image = render7)  
        self.canvas7.grid(row = 7, column = 0,columnspan=3,sticky=W+E)
        #myText=self.canvas7.create_text(100,50,text='SheMingLi')


        #画图框架图8
        self.canvas8 = Canvas(self, width = 200, height = 46, bg = "#f0fff0")
        #self.canvas8.create_rectangle(5,10,460,100,outline = 'red',dash = 10,fill = '#fff8dc')
        load8 = Image.open(r".\cfg\python_8")
        #print(load8.format,int(load8.size[0]/3*2),int(load8.size[1]/3*2),load8.mode)
        render8 = ImageTk.PhotoImage(load8)
        #img8 = load8.resize((456, 210),Image.ANTIALIAS)
        img8 = load8.resize((int(load8.size[0]/3*2),int(load8.size[1]/3*2)),Image.ANTIALIAS)
        render8 = ImageTk.PhotoImage(img8)
        self.canvas8.image =render8  #?—¢‰ï??•Ð?Ž¦o—ˆ
        self.canvas8.create_image(232,25,image = render8)  
        self.canvas8.grid(row = 8, column = 0,columnspan=3,sticky=W+E)
        #myText=self.canvas8.create_text(100,50,text='SheMingLi')




        #画图框架图9
        self.canvas9 = Canvas(self, width = 200, height = 46, bg = "#f0fff0")
        #self.canvas9.create_rectangle(5,10,460,100,outline = 'red',dash = 10,fill = '#fff8dc')
        load9 = Image.open(r".\cfg\python_9")
        #print(load9.format,int(load9.size[0]/3*2),int(load9.size[1]/3*2),load9.mode)
        render9 = ImageTk.PhotoImage(load9)
        #img9 = load9.resize((456, 210),Image.ANTIALIAS)
        img9 = load9.resize((int(load9.size[0]/3*2),int(load9.size[1]/3*2)),Image.ANTIALIAS)
        render9 = ImageTk.PhotoImage(img9)
        self.canvas9.image =render9  #?—¢‰ï??•Ð?Ž¦o—ˆ
        self.canvas9.create_image(232,25,image = render9)  
        self.canvas9.grid(row = 9, column = 0,columnspan=3,sticky=W+E)
        #myText=self.canvas9.create_text(100,50,text='SheMingLi')


        #画图框架图12  cc提示
        self.canvas12 = Canvas(self, width = 200, height = 70, bg = "#f0fff0")
        #self.canvas12.create_rectangle(5,10,460,100,outline = 'red',dash = 10,fill = '#fff8dc')
        self.canvas12.grid(row = 10, column = 0,columnspan=3,sticky=W+E)
        myText=self.canvas12.create_text(172,40,text='点击[cc]按钮,将自动修改cc格式。从下面格式开始修改:\n変更リスト:\n左:変更前 \n右:変更後',fill='red')        


        #画图框架图10
        self.canvas10 = Canvas(self, width = 200, height = 30, bg = "#f0fff0")
        #self.canvas10.create_rectangle(5,10,460,100,outline = 'red',dash = 10,fill = '#fff8dc')
        self.canvas10.grid(row = 11, column = 0,columnspan=3,sticky=W+E)
        myText=self.canvas10.create_text(122,17,text='点击[全部]按钮,将修改整个文书内容的格式',fill='red')


        #画图框架图11
        self.canvas11 = Canvas(self, width = 200, height = 30, bg = "#f0fff0")
        #self.canvas11.create_rectangle(5,10,460,100,outline = 'red',dash = 10,fill = '#fff8dc')
        self.canvas11.grid(row = 12, column = 0,columnspan=3,sticky=W+E)
        myText=self.canvas11.create_text(122,17,text='点击[选择]按钮,将修改光标选中内容的格式',fill='red')










        
        
        
        #帮助按钮设置
        self.HelpButton = Button(self, text = "Help",height = 1,width = 3,relief=FLAT,fg='blue',bg = '#ff0000',cursor = "heart",command = self.helpdoc)
        self.HelpButton.grid(row = 13, column = 3,pady = 5,sticky=E)


        #修改按钮
        self.buttonHead = Button(self, text = "hd",height = 1,width = 3,relief=RIDGE,fg='blue',bg = '#7cfc00',cursor = "exchange",command = self.button_Head)
        self.buttonHead.grid(row = 1, column = 3,pady = 5,sticky=E)


        self.buttonNo = Button(self, text = "NN",height = 1,width = 3,relief=RIDGE,fg='blue',bg = '#7cfc00',cursor = "exchange",command = self.button_No)
        self.buttonNo.grid(row = 2, column = 3,pady = 5,sticky=E)


        self.buttonSYD = Button(self, text = "DDD",height = 1,width = 3,relief=RIDGE,fg='blue',bg = '#7cfc00',cursor = "exchange",command = self.button_SYD)
        self.buttonSYD.grid(row = 3, column = 3,pady = 5,sticky=E)


        self.button1 = Button(self, text = "1",height = 1,width = 3,relief=RIDGE,fg='blue',bg = '#7cfc00',cursor = "exchange",command = self.button1)
        self.button1.grid(row = 4, column = 3,pady = 5,sticky=E)
        
        self.button2 = Button(self, text = "2",height = 1,width = 3,relief=RIDGE,fg='blue',bg = '#7cfc00',cursor = "exchange",command = self.button2)
        self.button2.grid(row = 5, column = 3,pady = 5,sticky=E)


        self.button3 = Button(self, text = "3",height = 1,width = 3,relief=RIDGE,fg='blue',bg = '#7cfc00',cursor = "exchange",command = self.button3)
        self.button3.grid(row = 6, column = 3,pady = 5,sticky=E)


        self.button4 = Button(self, text = "4",height = 1,width = 3,relief=RIDGE,fg='blue',bg = '#7cfc00',cursor = "exchange",command = self.button4)
        self.button4.grid(row = 7, column = 3,pady = 5,sticky=E)


        self.button5 = Button(self, text = "5",height = 1,width = 3,relief=RIDGE,fg='blue',bg = '#7cfc00',cursor = "exchange",command = self.button5)
        self.button5.grid(row = 8, column = 3,pady = 5,sticky=E)


        self.button6 = Button(self, text = "6",height = 1,width = 3,relief=RIDGE,fg='blue',bg = '#7cfc00',cursor = "exchange",command = self.button6)
        self.button6.grid(row = 9, column = 3,pady = 5,sticky=E)


        self.buttonSrc = Button(self, text = "NN",height = 1,width = 3,relief=RIDGE,fg='blue',bg = '#7cfc00',cursor = "exchange",command = self.button_Source)
        self.buttonSrc.grid(row = 10, column = 3,pady = 5,sticky=E)
        
        self.buttonAll = Button(self, text = "全部",height = 1,width = 3,relief=RIDGE,fg='blue',bg = '#7cfc00',cursor = "exchange",command = self.button_All)
        self.buttonAll.grid(row = 11, column = 3,pady = 5,sticky=E)


        self.buttonSelect = Button(self, text = "选择",height = 1,width = 3,relief=RIDGE,fg='blue',bg = '#7cfc00',cursor = "exchange",command = self.button_Select)
        self.buttonSelect.grid(row = 12, column = 3,pady = 5,sticky=E)




    def get_Num(self,head,number):
        global LST_1
        num = ['NULL','NULL']
        try:
            #print('当前章节数 = ' + str(Application.WordApp.ActiveDocument.ListParagraphs.Count ))
            #print('当前段落数 = ' + str(Application.WordApp.ActiveDocument.Paragraphs.Count ))
            #将readCfgFile1_1()得到的列表进行解析
            print('该章节的头部分:' + LST_2[number])
            print('下一章节的头部分:' + LST_1[head +1])


            for i in range(1,Application.WordApp.ActiveDocument.Paragraphs.Count + 1):
                #print('第' + str(i) +'段落=' )
                #print(Application.WordApp.ActiveDocument.Paragraphs(i))
                ls = str(Application.WordApp.ActiveDocument.Paragraphs(i))
                if ls[0:len(LST_2[number])] == LST_2[number]:  #该章节头,本章节的2号头即lst2的
                    #print('找到第' + str(i) + '段头位置')
                    num[0] = i
                    #break
                if ls[0:len(LST_1[head + 1])] == LST_1[head + 1]:#该章节的尾,下一章节的头即lst1的内容
                    #print('找到第' + str(i) + '段尾位置')
                    num[1] = i
                    break
            #print(num)
            LINE_NUM[head-1] = num
            #print(LINE_NUM)
            #print(LINE_NUM[head-1][0])
            #print(LINE_NUM[head-1][1])
            #self.format_Process(LINE_NUM[head-1][0],LINE_NUM[head-1][1])


        except : #如果文档没打开,则报AttributeError:无ActiveDocument属性错误
            Application.yn=tkinter.messagebox.showwarning(title='友情提醒',message='未选择docx文件,请点击<docx选择>')




        
        if head>=8 and head <=9:  #此处由于表头跟章节处理不一样。为了能将整个表格选择完,需要对range范围调整。range在函数format_Process函数中处理
            self.format_Process(LINE_NUM[head-1][0]-1,LINE_NUM[head-1][1])
        elif head ==10:
            self.format_Process(LINE_NUM[head-1][0]-1,LINE_NUM[head-1][1]+1)
        else:
            self.format_Process(LINE_NUM[head-1][0],LINE_NUM[head-1][1])


        


        


    def format_Process(self,head,tail):
        #print('head = '+ str(head))
        #print('tail = '+ str(tail))


        
        x = Application.WordApp.ActiveDocument.Paragraphs(head + 1).Range.Start
        y = Application.WordApp.ActiveDocument.Paragraphs(tail -1).Range.End
        #print('x = ' + str(x))
        #print('y = ' + str(y))
        #print('ok')
        
        Rg = Application.doc.Range(x, y) # 取得Range物件,範圍為文件的最開頭
        select = Rg.Select()  # 將range的範圍全部選取。並且取得
        
        #print(select)


        Rg.Font.Name = "黑体"# 字体
        #print('字体: ')
        #print(Rg.Font.Name)
        Rg.Font.Size = 10   # 字大
        Rg.ParagraphFormat.SpaceBefore  = 0#;//段前间距
        Rg.ParagraphFormat.SpaceAfter = 0#;//段后间距


        #Rg.ParagraphFormat.LineSpacing = 15   # 设置行距,1行=15磅
        #Rg.ParagraphFormat.Alignment = 0      # 段落对齐,0=左对齐,1=居中,2=右对齐




    def button_Head(self):
        #print('button_Head  ok')
        self.get_Num(8,8)
        Application.yn=tkinter.messagebox.showinfo(title='友情提醒',message='处理完成,请继续下一步操作^_^')
        
    
    def button_No(self):
        #print('button_No  ok')
        self.get_Num(9,9)
        Application.yn=tkinter.messagebox.showinfo(title='友情提醒',message='处理完成,请继续下一步操作^_^')
        
    def button_SYD(self):
        #print('button_No  ok')
        self.get_Num(10,10)
        Application.yn=tkinter.messagebox.showinfo(title='友情提醒',message='处理完成,请继续下一步操作^_^')
        
    def button1(self):
        #print('button 1  ok')
        self.get_Num(1,1)
        Application.yn=tkinter.messagebox.showinfo(title='友情提醒',message='处理完成,请继续下一步操作^_^')
        


    def button2(self):
        #print('button 2  ok')
        self.get_Num(2,2)
        Application.yn=tkinter.messagebox.showinfo(title='友情提醒',message='处理完成,请继续下一步操作^_^')
        
    def button3(self):
        #print('button 3  ok')
        self.get_Num(3,3)
        Application.yn=tkinter.messagebox.showinfo(title='友情提醒',message='处理完成,请继续下一步操作^_^')
        
    def button4(self):
        #print('button 4  ok')
        self.get_Num(4,4)
        Application.yn=tkinter.messagebox.showinfo(title='友情提醒',message='处理完成,请继续下一步操作^_^')
        
    def button5(self):
        #print('button 5  ok')
        self.get_Num(5,5)
        Application.yn=tkinter.messagebox.showinfo(title='友情提醒',message='处理完成,请继续下一步操作^_^')
        
    def button6(self):
        #print('button 6  ok')
        self.get_Num(6,6)
        Application.yn=tkinter.messagebox.showinfo(title='友情提醒',message='处理完成,请继续下一步操作^_^')
    
    def button_All(self):
        self.get_Num(8,8)
        self.get_Num(9,9)
        self.get_Num(10,10)
        self.get_Num(1,1)
        self.get_Num(2,2)
        self.get_Num(3,3)
        self.get_Num(4,4)
        self.get_Num(5,5)
        self.get_Num(6,6)
        Application.yn=tkinter.messagebox.showinfo(title='友情提醒',message='处理完成,请继续你的表演^_^')
     
    def button_Select(self):
        Application.sel = Application.WordApp.Selection  #不选择,返回光标的下一个字符
        #print('选择的doc文档名称 = ',end ='')
        #print(Application.sel.Document.FullName)
        #print('当前段落数 = ' + str(Application.WordApp.ActiveDocument.ListParagraphs.Count ))
        
        print('光标选的内容: ')
        print(Application.sel)
  


        Application.sel.Font.Name = "黑体"# 字体
        print('字体: ')
        print(Application.sel.Font.Name)
        Application.sel.Font.Size = 10   # 字大
        Application.sel.ParagraphFormat.SpaceBefore  = 10#;//段前间距
        Application.sel.ParagraphFormat.SpaceAfter = 10#;//段后间距


        #Application.sel.ParagraphFormat.LineSpacing = 15   # 设置行距,1行=15磅
        #Application.sel.ParagraphFormat.Alignment = 0      # 段落对齐,0=左对齐,1=居中,2=右对齐
        Application.yn=tkinter.messagebox.showinfo(title='友情提醒',message='处理完成,请继续你的表演^_^')
        
    def get_delete_No(self,tab):
        rangeNo_1 = 0
        RgTxt = ''
        if tab == Head_Tab:
            try:
                if LINE_NUM[5][1] == 'NULL':  #获取第一个表头的起始位置。即第x章之后内容。
                    #print('exe self.get_Num(6,6) =' + str(LINE_NUM[5][1]))
                    self.get_Num(6,6)
                    rangeNo_1 = LINE_NUM[5][1]
                else:
                    #print(' no exe self.get_Num(6,6) =' + str(LINE_NUM[5][1]))
                    rangeNo_1 = LINE_NUM[5][1]
                
                x = Application.WordApp.ActiveDocument.Paragraphs(rangeNo_1 + 2).Range.End # +3防止删除左右
                y = Application.WordApp.ActiveDocument.Tables.Item(tab).Range.Start - 1
                #print('x = ' + str(x))
                #print('y = ' + str(y))
                #print('ok')
                
                Rg = Application.doc.Range(x, y)
                #Rg = Application.doc.Range(13916, Application.WordApp.ActiveDocument.Tables.Item(tab).Range.Start -1)
                RgTxt = str(Rg)
                #print(RgTxt)
                ReGetFile = re.compile('(src\S*)')#找到1.1章节
                FilePath = ReGetFile.findall(str(RgTxt))
                print('文件路径:' + str(FilePath[0]))
                if FilePath != '':
                    select = Rg.Select()
                    Rg.InsertAfter('o.' + str(tab -Head_Tab +1) + '\n' + FilePath[0])
                    Rg.Font.Name = "黑体"# 字体
                    #print('字体: ')
                    #print(Rg.Font.Name)
                    Rg.Font.Size = 10   # 字大
                    Application.WordApp.Selection.Delete()
                    Application.doc.Range(Application.WordApp.ActiveDocument.Tables.Item(tab).Range.Start, Application.WordApp.ActiveDocument.Tables.Item(tab).Range.Start).Select()#书签定位
                    Application.WordApp.ActiveDocument.Bookmarks.Add("pyNo"+str(tab -Head_Tab + 1))
            except:
                traceback.print_exc()
                Application.yn=tkinter.messagebox.showwarning(title='友情提醒',message='第一个cc表有问题:\n1.表中不能有合并单元格\n2.关键字^_^')
                
        else:
            try:
                #Rg = Application.doc.Range(x, y)
                Rg = Application.doc.Range(Application.WordApp.ActiveDocument.Tables.Item(tab-1).Range.End + 1, Application.WordApp.ActiveDocument.Tables.Item(tab).Range.Start -1)
                RgTxt = str(Rg)
                #print(RgTxt)
                ReGetFile = re.compile('(src\S*)')#找到1.1章节
                FilePath = ReGetFile.findall(str(RgTxt))
                print('文件路径:' + str(FilePath[0]))
                if FilePath != '':
                    select = Rg.Select()
                    Rg.InsertAfter('o.' + str(tab -Head_Tab +1) + '\n' + FilePath[0])
                    
                    Rg.Font.Name = "黑体"# 字体
                    #print('字体: ')
                    #print(Rg.Font.Name)
                    Rg.Font.Size = 10   # 字大
                    
                    Application.WordApp.Selection.Delete()
                    Application.doc.Range(Application.WordApp.ActiveDocument.Tables.Item(tab).Range.Start, Application.WordApp.ActiveDocument.Tables.Item(tab).Range.Start).Select()#书签定位
                    Application.WordApp.ActiveDocument.Bookmarks.Add("pyNo"+str(tab -Head_Tab + 1))
            except:
                traceback.print_exc()
                Application.yn=tkinter.messagebox.showwarning(title='友情提醒',message='第'+ str(tab -Head_Tab +1) + '关键字^_^')
            


        
                
    
    def mark_process(self,h1,Vd,r,txt,r_count,tab):
        if r_count ==1:
            VdMoreLine = Vd
            
        else:
            VdMoreLine = Vd + (r_count)*h1/2-h1/2
        #Vd_2 = Vd + (r-1)*h1 - h1/4
        Vd_2 = VdMoreLine  - 0.3*h1 + 1.5/4
        #print('Vd_2 = ' + str(Vd_2))        
        Application.WordApp.ActiveDocument.Shapes.AddTextbox(1, 1080, Vd_2, 80, 1.6*h1).Select()# 1:是矩形。起点:水平 ,垂直  终点:以起点开始 #以磅为单位180
        Application.WordApp.Selection.ShapeRange.Line.ForeColor.RGB = 255 #红色
        Application.WordApp.Selection.ShapeRange.Line.Visible = True
        Application.WordApp.Selection.ShapeRange.Line.Weight = 1.5# 线粗1.5
        Application.WordApp.Selection.ShapeRange.Line.Style = 1#单线


        Application.WordApp.Selection.ShapeRange.TextFrame.MarginLeft = 0#以磅为单位返回或设置从文本框左边界到包含文本的形状中内接矩形左边界的距离。可读写。Single 类型。
        Application.WordApp.Selection.ParagraphFormat.LineSpacing = 12
        if txt == 1:
            Application.WordApp.Selection.Text = '「N1'+ str(tab -Head_Tab +1) +'」ddd'
            
        if txt == 2:
            Application.WordApp.Selection.Text = '「N1'+ str(tab -Head_Tab +1) +'」xxx'
        if txt == 3:
            Application.WordApp.Selection.Text = '「N1'+ str(tab -Head_Tab +1) +'」bbb'
            


        #Vd_1 = Vd + (r-1)*h1 + h1/2
        Vd_1 = Vd_2  + 1.6*h1/2
        Application.WordApp.ActiveDocument.Shapes.AddConnector(1, 1080, Vd_1, -66, 0).Select()#193
        Application.WordApp.Selection.ShapeRange.Line.EndArrowheadStyle = 2 #将直线加箭头
        Application.WordApp.Selection.ShapeRange.Line.ForeColor.RGB = 255
        Application.WordApp.Selection.ShapeRange.Line.Visible = True
        Application.WordApp.Selection.ShapeRange.Line.Weight = 1.5#


        h1MoreLine = h1 * r_count
        Application.WordApp.ActiveDocument.Shapes.AddShape(32,1008, Vd, 6, h1MoreLine).Select()#添加右大括号  1 2 3宽窄 4高度
        Application.WordApp.Selection.ShapeRange.Line.ForeColor.RGB = 255 #红色
        Application.WordApp.Selection.ShapeRange.Line.Visible = True
        Application.WordApp.Selection.ShapeRange.Line.Weight = 1.5# 线粗1.5
        Application.WordApp.Selection.ShapeRange.Line.Style = 1#单线


        
    def button_Source(self):
        global Head_Tab
        global head_tab_falg
        head_table_last = 0
        print('共计表格书 = ',end = '')
        print(Application.WordApp.ActiveDocument.Tables.Count)


        #print('表格水平位置 = ' ,end ='')
        #print(Application.WordApp.Selection.Information(5))
        #返回所选内容或区域的垂直位置,即所选内容的上边缘与页面的上边缘之间的距离,
        #以磅为单位(1 磅 = 20 缇,72 磅 = 1 英寸)。
        #如果所选内容未显示在文档窗口中,则该参数返回 -1。
        #print('表格垂直位置 = ' ,end ='')
        #print(Application.WordApp.Selection.Information(6))
        #Vd = Application.WordApp.Selection.Information(6)
        #print('Vd = '+ str(Vd))
 
        
        
        head_tab_falg = True#下次点击cc按钮重新进入
        for i in range(2,Application.WordApp.ActiveDocument.Tables.Count + 1):  #遍历各个表格,查找是否是cc表格,
            #print('正在处理表' + str(i))
            proFlag = False
            try:
                for r in range(1,Application.WordApp.ActiveDocument.Tables.Item(i).Rows.Count+1):
                        rowstr = str(Application.WordApp.ActiveDocument.Tables.Item(i).Cell(r,3))[0:-2]
                        if ((rowstr == " ") or (rowstr == "=" )  or (rowstr == "-+") or (rowstr == "+-") or (rowstr == "<>")):
                            if (rowstr == " "):
                                #print("是cc表的第" + str(i) + '个表的第' + str(r) + '行第3列 = *'  )
                                pass
                            else:
                                #print("是cc表的第" + str(i) + '个表的第' + str(r) + '行第3列 = ' + rowstr )
                                pass
                            proFlag = True
                            break;
                            #pass
                        else:
                            #print("不是是cc表的第" + str(i) + '个表的第' + str(r) + '行第3列 = ' + rowstr )
                            print("第" + str(i) + '个表不是是ccc表' )
                            proFlag = False
                            #pass


                if proFlag == True:  #如果是cc表格,进行列宽设置,及式样设置
                         #print('head_tab_falg1 = ' + str(head_tab_falg))
                         if head_tab_falg  == True:
                            head_tab_falg = False
                            head_table_last = i
                            #Head_Tab = i
                            #print('head_table_last = ' + str(head_table_last))
                                
                         #print('head_tab_falg2 = ' + str(head_tab_falg))
                         Head_Tab = head_table_last #只有重新点击cc按钮,才会获取
                         #print('Head_Tab = ' + str(Head_Tab))


                         #处理表头内容
                         self.get_delete_No(i)
                         #print(Application.WordApp.ActiveDocument.Tables.Item(i).Select)
                         x = Application.WordApp.ActiveDocument.Tables.Item(i).Range.Start
                         y = Application.WordApp.ActiveDocument.Tables.Item(i).Range.End   
                         Rg = Application.doc.Range(x, y) # 取得Range物件,範圍為文件的最開頭
                         #print(Rg)
                         #select = Rg.Select()#测试选择table
                      
                         Rg.Style = Application.WordApp.ActiveDocument.Styles("yanshi1") #先设定格式。不然列宽设置之后,表格还是比较宽。不变化
                         #print('开始设置列宽')
                         Application.WordApp.ActiveDocument.Tables.Item(i).Columns(1).SetWidth(1*28.35, 0)   # 调整第1列宽度,1cm=28.35pt
                         Application.WordApp.ActiveDocument.Tables.Item(i).Columns(2).SetWidth(18*28.35, 0)   # 调整第2列宽度
                         Application.WordApp.ActiveDocument.Tables.Item(i).Columns(3).SetWidth(1*28.35, 0)   # 调整第2列宽度
                         Application.WordApp.ActiveDocument.Tables.Item(i).Columns(4).SetWidth(1*28.35, 0)   # 调整第2列宽度
                         Application.WordApp.ActiveDocument.Tables.Item(i).Columns(5).SetWidth(18*28.35, 0)   # 调整第2列宽度




                         Application.WordApp.ActiveDocument.Tables(i).Select() #无此选择,下面的对话框无法出来
                         #print('正在处理表' + str(i))
                
                         Application.WordApp.Dialogs(1080).Show()#显示表格属性对话框。
                         #重置光标位置,防止重复出现选中部分刷屏
                         Application.doc.Range(Application.WordApp.ActiveDocument.Tables.Item(i).Range.Start, Application.WordApp.ActiveDocument.Tables.Item(i).Range.Start).Select()


                         try:
                                 #设置上下左右边框线条                     
                                 #Application.WordApp.ActiveDocument.Tables(i).Borders(-1)
                                 Application.WordApp.ActiveDocument.Tables(i).Borders(-1).LineStyle = 1
                                 Application.WordApp.ActiveDocument.Tables(i).Borders(-1).LineWidth = 4
                                 Application.WordApp.ActiveDocument.Tables(i).Borders(-1).Color = 0
                                 
                                 #Application.WordApp.ActiveDocument.Tables(i).Borders(-2)
                                 Application.WordApp.ActiveDocument.Tables(i).Borders(-2).LineStyle = 1
                                 Application.WordApp.ActiveDocument.Tables(i).Borders(-2).LineWidth = 4
                                 Application.WordApp.ActiveDocument.Tables(i).Borders(-2).Color = 0
                                
                                 #Application.WordApp.ActiveDocument.Tables(i).Borders(-3)
                                 Application.WordApp.ActiveDocument.Tables(i).Borders(-3).LineStyle = 1
                                 Application.WordApp.ActiveDocument.Tables(i).Borders(-3).LineWidth = 4
                                 Application.WordApp.ActiveDocument.Tables(i).Borders(-3).Color = 0
                    
                                 #Application.WordApp.ActiveDocument.Tables(i).Borders(-4)
                                 Application.WordApp.ActiveDocument.Tables(i).Borders(-4).LineStyle = 1
                                 Application.WordApp.ActiveDocument.Tables(i).Borders(-4).LineWidth = 4
                                 Application.WordApp.ActiveDocument.Tables(i).Borders(-4).Color = 0
                                 """
                                 Application.WordApp.ActiveDocument.Tables(i).Borders(-5).LineStyle = 1
                                 Application.WordApp.ActiveDocument.Tables(i).Borders(-5).LineWidth = 4
                                 Application.WordApp.ActiveDocument.Tables(i).Borders(-5).Color = 0                     


                                 Application.WordApp.ActiveDocument.Tables(i).Borders(-6).LineStyle = 1
                                 Application.WordApp.ActiveDocument.Tables(i).Borders(-6).LineWidth = 4
                                 Application.WordApp.ActiveDocument.Tables(i).Borders(-6).Color = 0
                                 """
                                 #Rg.Style = Application.WordApp.ActiveDocument.Styles("ソースcc")
                         except:
                             print('无法处理表格边框!请尝试设置表格属性,单元格间距选择中☑→□')
        
                         h1 = 3.8*28.35/10
                         
                         for r in range(1,Application.WordApp.ActiveDocument.Tables.Item(i).Rows.Count+1):#设置每行行高为固定值,方便插入mark
                            Application.WordApp.ActiveDocument.Tables.Item(i).Rows(r).Height = h1
                            
                            #print('表格高度1 = ' ,end ='')
                            #print(h1)
                         
                         for r in range(1,Application.WordApp.ActiveDocument.Tables.Item(i).Rows.Count+1):
                             rowstr2 = str(Application.WordApp.ActiveDocument.Tables.Item(i).Cell(r,3))[0:-2]
                             space_count = 0
                             r_count = 1
                             
                             Rg1 = Application.WordApp.ActiveDocument.Tables.Item(i).Cell(r,3)
                             select = Rg1.Select()
                             #print(Rg1)
                             #Application.WordApp.ActiveDocument.Tables.Item(i).Rows(r).Height = h1
                             
                             Rg2 = Application.WordApp.ActiveDocument.Tables.Item(i).Rows(r)
                             #print(Rg2)
                             select = Rg2.Select()                             
                             Vd31 = Application.WordApp.Selection.Information(6)
                             #print('表的垂直高度Vd31 = '+ str(Vd31))                            


                             pageStart = Application.WordApp.Selection.Information(3)
                             #print('表的页码page = '+ str(pageStart))
                             pageflag = True
                             pageNow = 0
                             pageProcess = False
                             if ((rowstr2 == "-+") or (rowstr2 == "+-") or (rowstr2 == "<>")):
                                
                                print('正在处理第' + str(i - Head_Tab + 1)+'个cc表的第行' + str(r) + '的变更点')
                                
                                if(r == Application.WordApp.ActiveDocument.Tables.Item(i).Rows.Count):#如果是最后一行,不处理
                                    pass
                                else:
                                    while(str(Application.WordApp.ActiveDocument.Tables.Item(i).Cell(r+ space_count + 1,3))[0:-2] == " "):                                      
                                        space_count =space_count + 1 #用于行递加功能
                                        
                                        if(r+ space_count > Application.WordApp.ActiveDocument.Tables.Item(i).Rows.Count):#超过行号
                                            print('到行尾……')
                                            break
                                        else:
                                            r_count = r_count + 1 #用于计数相同行数
                                            #print('r+ space_count+1 = ' + str(r+ space_count))
                                            Rgpage = Application.WordApp.ActiveDocument.Tables.Item(i).Rows(r+ space_count)
                                            select = Rgpage.Select()                             
                                            pageStop = Application.WordApp.Selection.Information(3)
                                            #print('表的页码stoppage = '+ str(pageStop))
                                            if (pageStart != pageStop) and (pageflag == True):
                                                pageNow = space_count 
                                                #print('上一页占据行数pageNow = '+ str(pageNow))
                                                pageflag = False
                                                pageProcess = True
                                
                                #print('r_count = '  + str(r_count))
                                Application.WordApp.ActiveDocument.Tables.Item(i).Rows(r).Select()  #重置光标
                                if ((rowstr2 == "-+")): #追加 =1
                                     #self.mark_process(h1,Vd31,r,2,r_count)
                                     if pageProcess == True:
                                         self.mark_process(h1,Vd31,r,1,pageNow,i)
                                         Application.WordApp.ActiveDocument.Tables.Item(i).Rows(r + pageNow).Select()
                                         VdTemp = Application.WordApp.Selection.Information(6)
                                         self.mark_process(h1,VdTemp,r,1,r_count- pageNow,i)
                                     else:
                                          self.mark_process(h1,Vd31,r,1,r_count,i)
                                    


                                if ((rowstr2 == "+-")): #消除 =2
                                    #self.mark_process(h1,Vd31,r,2,r_count)
                                    if pageProcess == True:
                                         self.mark_process(h1,Vd31,r,2,pageNow,i)
                                         Application.WordApp.ActiveDocument.Tables.Item(i).Rows(r + pageNow).Select()
                                         VdTemp = Application.WordApp.Selection.Information(6)
                                         self.mark_process(h1,VdTemp,r,2,r_count- pageNow,i)
                                    else:
                                         self.mark_process(h1,Vd31,r,2,r_count,i)


                                if ((rowstr2 == "<>")): #变更= 3
                                    #self.mark_process(h1,Vd31,r-45,3,r_count)
                                    if pageProcess == True:
                                         self.mark_process(h1,Vd31,r,3,pageNow,i)
                                         Application.WordApp.ActiveDocument.Tables.Item(i).Rows(r + pageNow).Select()
                                         VdTemp = Application.WordApp.Selection.Information(6)
                                         self.mark_process(h1,VdTemp,r,1,r_count - pageNow,i)
                                    else:
                                         self.mark_process(h1,Vd31,r,3,r_count,i)
                             
                
            except:
                 traceback.print_exc()
                 if proFlag == True:
                     print('第' + str(i - Head_Tab + 1) + '个cc表:无法处理!请确认表中是否有合并单元格!')
                 if proFlag == False:
                     print('第' + str(i) + '个表:无法处理!如果不是cc表请忽略!')
    


       
    def helpdoc(self):
        tkinter.messagebox.showinfo(title='工具帮助1.0',message='☆版本信息:\n    Version1.0\n ')
        print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))


        




    def selectDocx(self):
        Application.filename=tkinter.filedialog.askopenfilename(filetypes=[('docx|doc格式','*.docx;*.doc')])  #获取的docx文件路径
        #Application.filename= r'C:\UsersD5.doc'
        print(Application.filename)
        self.path2.set(Application.filename)


        #处理选择的doc文件格式
        Application.WordApp = win32com.client.Dispatch("Word.Application") # 载入WORD模块
        print('Application.WordApp = ',end ='')
        print(Application.WordApp)
        Application.WordApp.Visible = True           # 显示Word应用程序
        Application.doc = Application.WordApp.Documents.Open(Application.filename) # 打开指定文档


        readCfgFile1_1() #读取cfg中的1.1章节标记,以备分章使用
        readCfgFile1_2() #读取cfg中的1.2章节标记,以备分章使用
     


app = Application()
app.master.title('格式设定专用1.0')
app.master.geometry('510x960')
app.master.resizable(width=False,height=False)   # 固定长宽不可拉伸
app.mainloop()

猜你喜欢

转载自blog.csdn.net/daihuibing389/article/details/79911048