详细分析Python中的win32com(附Demo)

前言

对于自动化RPA比较火热,相应的库也比较多,此文分析win32com这个库,用于操作office

1. 基本知识

Win32com 是一个 Python 模块,是 pywin32 扩展的一部分,允许 Python 代码与 Windows COM(Component Object Model)对象进行交互

COM 是 Windows 平台上用于组件软件模型的技术,可以让不同的应用程序通过 COM 对象进行通信和操作

基本的API如下:

  1. Dispatch 函数用于创建一个 COM 对象的实例
    通过对象的 ProgID 来初始化 COM 对象
import win32com.client
excel = win32com.client.Dispatch("Excel.Application")
  1. GetActiveObject 函数用于连接到已经运行的 COM 对象
    通过对象的 ProgID 来连接到现有的 COM 对象实例
word = win32com.client.GetActiveObject("Word.Application")
  1. DispatchEx 类似于 Dispatch,但允许在不同的安全上下文中创建 COM 对象
excel = win32com.client.DispatchEx("Excel.Application")
  1. EnsureDispatch 函数与 Dispatch 类似,但如果无法创建对象,则会抛出更友好的异常
excel = win32com.client.gencache.EnsureDispatch("Excel.Application")
  1. WithEvents 函数用于绑定事件处理程序到 COM 对象
class ExcelEvents:
    def OnWorkbookOpen(self, wb):
        print("Workbook opened:", wb.Name)

excel = win32com.client.DispatchWithEvents("Excel.Application", ExcelEvents)

2. Excel

基本的Demo如下:
展示了如何使用 win32com 控制 Excel 应用程序,创建一个新工作簿,并向单元格中写入数据

import win32com.client

def main():
    # 创建 Excel 应用程序实例
    excel = win32com.client.Dispatch("Excel.Application")
    excel.Visible = True  # 使 Excel 界面可见

    # 创建一个新的工作簿
    workbook = excel.Workbooks.Add()
    sheet = workbook.Worksheets(1)

    # 向单元格中写入数据
    sheet.Cells(1, 1).Value = "Hello"
    sheet.Cells(1, 2).Value = "World"
    sheet.Cells(2, 1).Value = "Python"
    sheet.Cells(2, 2).Value = "Win32com"

    # 保存工作簿
    workbook.SaveAs(r"d:\Users\lixiaosong\ceshi.xlsx")

    # 关闭工作簿
    workbook.Close(False)  # False 表示不保存

    # 退出 Excel 应用程序
    excel.Quit()

if __name__ == "__main__":
    main()

截图如下:

在这里插入图片描述

对于上述的Demo,基本函数用法如下:

  1. 创建 Excel 应用程序实例excel = win32com.client.Dispatch("Excel.Application")
  2. 使 Excel 界面可见excel.Visible = True
  3. 创建一个新的工作簿workbook = excel.Workbooks.Add()
  4. 选择第一个工作表sheet = workbook.Worksheets(1)
  5. 向单元格中写入数据
  6. 保存工作簿workbook.SaveAs(r"C:\path\to\your\file.xlsx")
  7. 退出 Excel 应用程序excel.Quit()

3. Word

import win32com.client

def main():
    # 创建 Word 应用程序实例
    word = win32com.client.Dispatch("Word.Application")
    word.Visible = True  # 使 Word 界面可见

    # 创建一个新的文档
    doc = word.Documents.Add()

    # 向文档中写入文本
    range_obj = doc.Range(0, 0)
    range_obj.Text = "Hello World!\n"
    range_obj.InsertAfter("This is a demo of win32com in Python.\n")
    range_obj.InsertAfter("You can automate Word operations using Python scripts.\n")

    # 保存文档
    doc.SaveAs(r"d:\Users\lixiaosong\file.docx")

    # 关闭文档
    doc.Close(False)  # False 表示不保存

    # 退出 Word 应用程序
    word.Quit()

if __name__ == "__main__":
    main()

截图如下:

在这里插入图片描述

对于上述的Demo,基本函数用法如下:

  1. 创建 Word 应用程序实例word = win32com.client.Dispatch("Word.Application")

  2. 使 Word 界面可见word.Visible = True

  3. 创建一个新的文档doc = word.Documents.Add()

  4. 向文档中写入文本

  5. 保存文档doc.SaveAs(r"C:\path\to\your\file.docx")

  6. 关闭文档doc.Close(False)

  7. 退出 Word 应用程序word.Quit()

以上的Demo比较简易,如果想花里胡哨还可使用如下:

  • 插入段落:
paragraph = doc.Paragraphs.Add()
paragraph.Range.Text = "This is a new paragraph."
  • 设置文本格式:
range_obj.Font.Name = "Arial"
range_obj.Font.Size = 12
range_obj.Font.Bold = True
range_obj.Font.Italic = True
  • 插入表格
table = doc.Tables.Add(range_obj, 3, 3)
table.Cell(1, 1).Range.Text = "Row 1, Col 1"
table.Cell(1, 2).Range.Text = "Row 1, Col 2"
table.Cell(1, 3).Range.Text = "Row 1, Col 3"
  • 正文文字替换
find = doc.Content.Find
find.Text = "old text"
find.Replacement.Text = "new text"
find.Execute(Replace=2)
  • 页眉页脚文字替换:
header_range = doc.Sections(1).Headers(win32com.client.constants.wdHeaderFooterPrimary).Range
header_find = header_range.Find
header_find.Text = "old header text"
header_find.Replacement.Text = "new header text"
header_find.Execute(Replace=2)
  • 打印文档doc.PrintOut()

更多的Demo如下:

  1. 正文文字替换
import win32com.client

def main():
    word = win32com.client.Dispatch("Word.Application")
    word.Visible = True

    # 打开一个现有的文档
    doc = word.Documents.Open(r"C:\path\to\your\file.docx")

    # 进行文字替换
    find = doc.Content.Find
    find.Text = "old text"
    find.Replacement.Text = "new text"
    find.Execute(Replace=2)  # 2 表示 wdReplaceAll

    # 保存并关闭文档
    doc.Save()
    doc.Close(False)
    word.Quit()

if __name__ == "__main__":
    main()
  1. 页眉页脚文字替换
import win32com.client

def main():
    word = win32com.client.Dispatch("Word.Application")
    word.Visible = True

    # 打开一个现有的文档
    doc = word.Documents.Open(r"C:\path\to\your\file.docx")

    # 访问页眉
    header_range = doc.Sections(1).Headers(win32com.client.constants.wdHeaderFooterPrimary).Range
    header_find = header_range.Find
    header_find.Text = "old header text"
    header_find.Replacement.Text = "new header text"
    header_find.Execute(Replace=2)

    # 访问页脚
    footer_range = doc.Sections(1).Footers(win32com.client.constants.wdHeaderFooterPrimary).Range
    footer_find = footer_range.Find
    footer_find.Text = "old footer text"
    footer_find.Replacement.Text = "new footer text"
    footer_find.Execute(Replace=2)

    # 保存并关闭文档
    doc.Save()
    doc.Close(False)
    word.Quit()

if __name__ == "__main__":
    main()
  1. 打印文档
import win32com.client

def main():
    word = win32com.client.Dispatch("Word.Application")
    word.Visible = True

    # 打开一个现有的文档
    doc = word.Documents.Open(r"C:\path\to\your\file.docx")

    # 打印文档
    doc.PrintOut()

    # 关闭文档
    doc.Close(False)
    word.Quit()

if __name__ == "__main__":
    main()
  • 49
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

码农研究僧

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

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

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

打赏作者

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

抵扣说明:

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

余额充值