Python3--自动化办公

主要记一下Python对办公文件的简单处理,如word、excel、pdf、csv及ppt。因为内容比较多,不细究原理了,直接写应用吧~

Word

  1. 写入Word文件。注:使用了win32com模块,只能在win系统下使用...
    import win32com
    import win32com.client
    import os
    def makeWord(fileName,name):
        # 打开word应用程序
        word=win32com.client.Dispatch("Word.Application")
        #让文档可见
        word.Visible=True
        #创建文档
        doc=word.Documents.Add()
        #写内容,从头开始
        r=doc.Range(0,0)
        #开始插入内容
        r.InsertAfter("有人喜欢小溪,是因为没见过大海。")
        r.InsertAfter("我看过银河,可我只爱一粒星--"+name)
        #存储文件
        doc.SaveAs(path)
        #关闭文件 
        doc.Close()
        #退出word
        word.Quit()
    
    
    names=["张三","李四","王五"]
    for name in names:
        #获取当前绝对路径来存放文件
        path=os.path.join(os.getcwd(),name)
        makeWord(path,name)

     

     

     

  2. 读取Word文件
    import win32com
    import win32com.client
    import os
    
    def readWord(path):
        #调用系统word功能,可以处理doc和docx文件
        mw=win32com.client.Dispatch("Word.Application")
        #打开文件
        doc=mw.Documents.Open(path)
        for par in doc.Paragraphs:
            line=par.Range.Text
            print(line)
        #关闭
        doc.Close()
        #退出word
        mw.Quit()
    
    
    path = os.path.join(os.getcwd(),'张三.docx')
    readWord(path)
    #有人喜欢小溪,是因为没见过大海。我看过银河,可我只爱一粒星--张三

     

Excel

  1. 写入xls文件  注:这里使用了pyexcel_xls,需要另行安装(pip install pyexcel_xls)
    #有序字典
    from collections import OrderedDict
    from pyexcel_xls import save_data
    
    
    def makeExce(path,data):
        #有序字典
        dic = OrderedDict()
        for sheetName,sheetValue in data.items():
            d = {}
            d[sheetName] = sheetValue
            #此格式的有序字典,sheetName为子表名,sheetValue为表中的数据
            dic.update(d)
        #保存
        save_data(path,dic)
    
    
    path = r"C:\Users\Administrator\Desktop\make.xls"
    #只能写xls格式的excel文件
    makeExce(path,{"表1":[[1,2,3],[4,5,6]],"表2":[[11,22,33],[44,55,66]]})

     

  2. 读取xls 或 xlsx文件
    from collections import OrderedDict
    from pyexcel_xls import get_data
    
    
    def readXls(path):
        dic=OrderedDict()
        #抓取数据
        xdata=get_data(path)
        for sheet in xdata:
            dic[sheet]=xdata[sheet]
        #返回的是有序字典
        return dic
    
    
    path=r"C:\Users\Administrator\Desktop\make.xls"
    dic=readXls(path)
    print(dic['表1'][1])
    #[4, 5, 6]

     

PPT

  1. 写入PPT 
    import win32com
    import win32com.client
    
    
    def makePpt(path):
        ppt = win32com.client.Dispatch("PowerPoint.Application")
        # 让文档可见
        ppt.Visible = True
        #增加一个文件
        pptFile = ppt.Presentations.Add()
    
        #创建页 参数1为页数(从1开始)参数2为类型(主题)
        page1 = pptFile.Slides.Add(1,1)
        t1 = page1.Shapes[0].TextFrame.TextRange
        t1.Text = "sunck"
        t2 = page1.Shapes[1].TextFrame.TextRange
        t2.Text = "sunck is a good man"
        #保存
        pptFile.SaveAs(path)
        pptFile.close()
        ppt.Quit()
    
    
    path=r"C:\Users\Administrator\Desktop\make.ppt"
    makePpt(path) 

     

 

CSV

  1. 写csv文件
    import csv
    
    
    def writeCsv(path,data):
      #使用这个newline=""可以解决win下自动添加空行的问题
        with open(path, "w",newline="") as f:
            writer = csv.writer(f)
            for row in data:#整行写入,这里是二维列表,一个一维列表写为一行
                writer.writerow(row)
    
    
    path = r"C:\Users\Administrator\Desktop\make.csv"
    data = [['admin','admin','admin'],['byadmin','byadmin','byadmin'],['byadmin','byadmin','byadmin']]
    writeCsv(path,data)

     

     

  2. 读取csv文件

      
    import csv
    
    
    def readCsv(path):
        contentList = []
        with open(path,"r") as f:
            allFileInfo = csv.reader(f)
    
            for row in allFileInfo:
                contentList.append(row)
        return contentList
    path = r"C:\Users\Administrator\Desktop\make.csv"
    print(readCsv(path)) 
    #[['admin', 'admin', 'admin'], ['byadmin', 'byadmin', 'byadmin'], ['byadmin', 'byadmin', 'byadmin']]

     

PDF

  1. 读PDF  PDF转TXT需安装pdfminer3k(pip install pdfminer3k)
    import sys
    import importlib
    importlib.reload(sys)
    
    from pdfminer.pdfparser import PDFParser,PDFDocument
    from pdfminer.pdfinterp import PDFResourceManager,PDFPageInterpreter
    from pdfminer.converter import PDFPageAggregator
    from pdfminer.layout import LTTextBoxHorizontal,LAParams
    from pdfminer.pdfinterp import PDFTextExtractionNotAllowed
    
    
    def readPdf(path,toPath):
        f=open(path,"rb")
        #创建一个pdf文档分析器
        parser=PDFParser(f)
        #创建一个PDF文档
        pdfFile=PDFDocument()
    
        #连接分析器与文档对象
        parser.set_document(pdfFile)
        pdfFile.set_parser(parser)
    
        #提供初始化密码
        pdfFile.initialize()
    
        #检测文档是否提供txt转换
        if not pdfFile.is_extractable:
            raise PDFTextExtractionNotAllowed
        else:
            #解析数据
            #数据管理器
            manager=PDFResourceManager()
            #创建一个PDF设备的对象
            laparams=LAParams()
            device=PDFPageAggregator(manager,laparams=laparams)
            #解析器对象
            interpreter=PDFPageInterpreter(manager,device)
            #开始循环处理,每次处理一页
            for page in pdfFile.get_pages():
                interpreter.process_page(page)
                #处理图层
                layout=device.get_result()
                for x in layout:
                    if (isinstance(x,LTTextBoxHorizontal)):
                        with open(toPath,"a") as f:
                            str=x.get_text()
                            #print(str)
                            f.write(str+"\n")
    
    
    
    
    path=r"C:\Users\Administrator\Desktop\英语语法.pdf"
    toPath=r"C:\Users\Administrator\Desktop\res.txt"
    #从pdf文件提取字符保存到txt文件
    readPdf(path,toPath)

     

      
posted @ 2019-04-20 11:42  byadmin  阅读(5694)  评论(0编辑  收藏  举报