Use Python to read and write office documents

1. Use Python to create PPT and write content

#coding=utf-8
import os
import win32com
import win32com.client
def CreatePPTFile(FilePath):
    PPT = win32com.client.Dispatch("PowerPoint.Application")
    PPT.Visible = True
    # 创建一个文件
    PPTFile = PPT.Presentations.Add()
    # 创建页,参数1为页数,从1开始;参数2为类型
    PageOne = PPTFile.Slides.Add(1,1)
    t1 = PageOne.Shapes[0].TextFrame.TextRange
    t1.Text = "Sunck"
    t2 = PageOne.Shapes[1].TextFrame.TextRange
    t2.Text = "Sunck is a good man!"
    PageTwo = PPTFile.Slides.Add(2,2)
    t3 = PageTwo.Shapes[0].TextFrame.TextRange
    t3.Text = "第二页标题"
    t4 = PageTwo.Shapes[1].TextFrame.TextRange
    t4.Text = "第二页第一栏内容"

    # 保存
    PPTFile.SaveAs(FilePath)
    PPTFile.Close()
    PPT.Quit()
FilePath = r"\test.ppt"
CurrentPath = os.getcwd()

CreatePPTFile(CurrentPath+FilePath)

2. Use Python to create Word and write content

#coding=utf-8
# 创建Word文件
import win32com
import win32com.client
import os

def CreateWordFile(FilePath,Name):
    word = win32com.client.Dispatch("Word.Application")
    # 让文档可见
    word.Visible = True
    # 创建文档
    doc = word.Documents.Add()
    # 从头开始写内容
    r = doc.Range(0,0)
    r.InsertAfter("亲爱的" + Name + "\n")
    r.InsertAfter("        我想你。。。。\n")

    # 存储文件
    doc.SaveAs(FilePath)
    # 关闭文件
    doc.Close()
    word.Quit()
NameList = ['张三','李四','王五']
for Name in NameList:
    Filepath = Name
    CurrentPath = os.getcwd()
    AbsolutePath = os.path.join(CurrentPath,Filepath)
    CreateWordFile(AbsolutePath,Name)

3. Use Python to read the content in Word

#coding=utf-8
# 读取Doc与Docx文件
import win32com
import win32com.client
import os

def ReadWordFile(FilePath,ToFilePath):
    # 调用系统Word功能,可以处理doc和docx两种文件
    mw = win32com.client.Dispatch("Word.Application")
    # 打开文件
    doc = mw.Documents.Open(FilePath)
    doc.SaveAs(ToFilePath,2) # 2表示txt文件
    for paragraph in doc.Paragraphs:
        line = paragraph.Range.Text
        print(line)

    # 关闭文件
    doc.Close()
    # 退出Word
    mw.Quit()
FilePath = r"\test.docx"
CurrentPath = os.getcwd()
AbsolutePath = CurrentPath + FilePath
# 必须传入绝对路径
ToFilePath = r"\test.txt"
AbsoluteToFilePath = CurrentPath + ToFilePath
ReadWordFile(AbsolutePath,AbsoluteToFilePath)

Guess you like

Origin blog.csdn.net/zhuan_long/article/details/111615663