使用Python读取,写入office文档

1. 使用Python创建PPT并写入内容

#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. 使用Python创建Word并写入内容

#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. 使用Python读取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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

西门一刀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值