使用python操作word win32com

研究一下,利用win32com操作 word

WORD中最重要的概念有几个:
Application - 这个毫无疑问是我们的WORD应用程序
Document - 这个就是一个打开的文档对象
Range - 基本上所有对象都是有Range属性的,而这也为我们排版提供了极大的便利。。。
Paragraph - 顾名思义,这个是段落的意思,也就是我们文档中的一个段内容(可以是文本、图片等)。
Section - 怎么才能插入一个新的页,然后在新页上开始输出内容。。。
ParagraphFormat - 这个是为了设置格式的,你不可能不使用它。。。

 

from win32com.client import Dispatch
import win32com.client

# coding=utf-8
import win32com
from win32com.client import Dispatch, DispatchEx

wordApp = Dispatch('Word.Application')  # 打开word应用程序
# word = DispatchEx('Word.Application') #启动独立的进程
wordApp.Visible = 0  # 后台运行,不显示
wordApp.DisplayAlerts = 0  # 不警告
path = r"C:\Users\admin\Desktop\demo.doc"  # word文件路径
doc = wordApp.Documents.Open(FileName=path, Encoding='gbk')
# content = doc.Range(doc.Content.Start, doc.Content.End)
# content = doc.Range()
print('----------------')
print ('段落数: ', doc.Paragraphs.count)

# 利用下标遍历段落
for i in range(len(doc.Paragraphs)):
    para = doc.Paragraphs[i]
    print (para.Range.text)
print ('-------------------------')

# 直接遍历段落
for para in doc.paragraphs:
    print (para.Range.text)
    # print para  #只能用于文档内容全英文的情况

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

 

 1 import win32com
 2 from win32com.client import Dispatch, constants
 3 def fu(filename):
 4     wordApp = Dispatch('Word.Application')  # 打开word应用程序
 5     # word = DispatchEx('Word.Application') #启动独立的进程
 6     wordApp.Visible = 0  # 后台运行,不显示
 7     wordApp.DisplayAlerts = 0  # 不警告
 8     doc = wordApp.Documents.Open(filename, Encoding='gbk')
 9     # content = doc.Range(doc.Content.Start, doc.Content.End)
10     # content = doc.Range()
11     print('表格数: ', doc.Tables.count)
12     # doc.Tables(1).Rows(1).Cells(2).Range.Text="修改1表格1行2个单元格"
13     # doc.Tables(2).Rows(2).Cells(3).Range.Text = '修改2表格2行3个单元格'
14     # doc.Tables(1).Cell(2, 2).Range.InsertAfter('原内容保留')  # 插入,
15     # doc.Tables(1).Cell(2, 1).Range.Text = ('Some text')
16     # doc.Tables(1).Rows.Add()  # 在表格最下面     增加一行
17     # doc.Tables(1).Columns.Add()  # 增加一列
18     # doc.Tables[0].Rows.Add()  # 在表格最下面     增加一行  可以通过索引[0]
19     doc.Save()
20     doc.Close()  # 关闭word文档
21     # word.Quit  #关闭word程序
22 
23 if __name__=="__main__":
24     fu(r"C:\Users\admin\Desktop\demo.docx")
表格简单操作

 

API 参见MSDN,因为是通过COM调用的,所以API和MSDN上的一样。

https://docs.microsoft.com/en-us/dotnet/api/microsoft.office.interop.word?redirectedfrom=MSDN&view=word-pia

Word组件对象模型

 https://blog.csdn.net/wishfly/article/details/39959349

 参考资料

https://blog.csdn.net/jazywoo123/article/details/18356713


import win32com
from win32com.client import Dispatch,constants,DispatchEx


# 或使用下面的方法,启动独立进程
# WordApp=DispatchEx('Word.Application')
class ShuiWordApp:
    WordApp=Dispatch('Word.Application')
    WordApp.Visible = 1  # 调试阶段打开
    WordApp.DisplayAlerts = 0  ## 警告信息关闭
    def __init__(self,filename=None):
        self.filename=filename#文件名
        if self.filename:
            #如果给一个文件路径,就会打开这个文件
            self.docApp=self.WordApp.Documents.Open(self.filename)
        else:
            #如果不给一个文件路径,就会新建 一个文档
            self.docApp=self.WordApp.Documents.Add()

    def insert(self,string,row=0,column=0):#插入内容
        self.selectRange=self.docApp.Range(row,column)#获取光标位置 两个参数分别代表起始点,结束点
        self.selectRange.InsertBefore(string)
    # def insert_sections(self):
    #     section_index=0
    #     for i in range(10):
    #         pre_section=self.docApp.Secitons(section_index)
    #         new_seciton = self.docApp.Range(pre_section.Range.End, pre_section.Range.End).Sections.Add()
    #         new_range = new_seciton.Range
    #
    #         content_pg = new_range.Paragraphs.Add()
    #         content_pg.Range.Font.Name, content_pg.Range.Font.Size = 'Times New Roman', 24
    #         # caption_pg.Range.ParagraphFormat.Alignment = 0  # 0,1,2 分别对应左对齐、居中、右对齐
    #         # caption_pg.Range.InsertBefore('Hello,Page ' + str(i + 1))
    def add_table(self):
        pre_section = self.docApp.Secitons(0)#在第一页末尾价格表格
        new_seciton = self.docApp.Range(pre_section.Range.End, pre_section.Range.End).Sections.Add()
        new_range = new_seciton.Range
        new_table = new_range.Tables.Add(self.docApp.Range(new_range.End, new_range.End), 5, 5)  # 在文档末尾添加一个5*5的表格
    def select_paragraphs(self):
        print('段落数: ', self.docApp.Paragraphs.count)
        for i in range(len(self.docApp.Paragraphs)):# 利用下标遍历段落
            para = self.docApp.Paragraphs[i]
            print(i,para.Range.text)
        print('-------------------------')


    def page_header(self,string,*args):
        page_set = {'top': 9, 'bottom': 10, }
        header_set = {'left': 0, 'middle': 1, 'right': 2}
        a = 9
        b = 0
        for item in args:
            if item in page_set:
                a = page_set.get(item, 9)
                break
        for i in args:
            if i in header_set:
                b = header_set.get(i, 0)
                break
        self.WordApp.ActiveWindow.ActivePane.View.SeekView=a  # 设置页眉文字,如果要设置页脚值需要把SeekView由9改为10就可以了。。。
        self.WordApp.Selection.ParagraphFormat.Alignment=b
        self.WordApp.Selection.Text=string
        self.WordApp.ActiveWindow.ActivePane.View.SeekView = 0  # 释放焦点,返回主文档

    def save(self, newfilename=None):  # 保存文件
        if newfilename:
            self.filename = newfilename
            self.docApp.SaveAs(newfilename)
        else:
            self.docApp.Save()
    def printf(self):#打印文件
        self.docApp.PrintOut()

    def closeapp(self):#关闭程序
        self.docApp.Close(SaveChanges=0)
        self.WordApp.Quit()


if __name__=="__main__":
    app=ShuiWordApp(r"C:\Users\admin\Desktop\demo.docx")
    # for i in range(5):
    #     app.insert(">>>hello world!!\n\t")
    # app.page_header("水杉9",'bottom','right')
    app.select_paragraphs()
    app.add_table()
    app.save()
    app.closeapp()
未完。。。。
from win32com.client import Dispatch
import win32com.client

# coding=utf-8
import win32com
from win32com.client import Dispatch, DispatchEx

wordApp = Dispatch('Word.Application')  # 打开word应用程序
# word = DispatchEx('Word.Application') #启动独立的进程
wordApp.Visible = 0  # 后台运行,不显示
wordApp.DisplayAlerts = 0  # 不警告
path = r"C:\Users\admin\Desktop\demo.docx"  # word文件路径
doc = wordApp.Documents.Open(FileName=path)
# content = doc.Range(doc.Content.Start, doc.Content.End)
# content = doc.Range()
print('----------------')
print ('段落数: ', doc.Paragraphs.count)
# 直接遍历段落
for para in doc.paragraphs:
    print (para.Range.text)
    print(para.Style)#打印段落的类型 是正文还是标题1标题2。。。。


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

 https://www.cnblogs.com/findeasy/archive/2013/01/02/4053123.html

 https://www.cnblogs.com/oracleblogs/p/3387436.html

import win32com
from win32com.client import Dispatch, constants
def fu(filename):
    wordApp = Dispatch('Word.Application')  # 打开word应用程序
    # word = DispatchEx('Word.Application') #启动独立的进程
    wordApp.Visible = 0  # 后台运行,不显示
    wordApp.DisplayAlerts = 0  # 不警告
    doc = wordApp.Documents.Open(filename, Encoding='gbk')
    # content = doc.Range(doc.Content.Start, doc.Content.End)
    # content = doc.Range()
    # print('表格数: ', doc.Tables.count)
    # doc.Tables(1).Rows(1).Cells(2).Range.Text="修改1表格1行2个单元格"
    # doc.Tables(2).Rows(2).Cells(3).Range.Text = '修改2表格2行3个单元格'
    # doc.Tables(1).Cell(2, 2).Range.InsertAfter('原内容保留')  # 插入,
    # doc.Tables(1).Cell(2, 1).Range.Text = ('Some text')
    # doc.Tables(1).Rows.Add()  # 在表格最下面     增加一行
    # doc.Tables(1).Columns.Add()  # 增加一列
    # doc.Tables[0].Rows.Add()  # 在表格最下面     增加一行  可以通过索引[0]
    doc.Save()
    doc.Close()  # 关闭word文档
    # word.Quit  #关闭word程序

if __name__=="__main__":
    fu(r"C:\Users\admin\Desktop\demo.docx")
View Code

 


# coding=utf-8
import win32com
from win32com.client import Dispatch, DispatchEx

wordApp = Dispatch('Word.Application')  # 打开word应用程序
wordApp.Visible = 1  # 后台运行,不显示
wordApp.DisplayAlerts = 0  # 不警告
doc = wordApp.Documents.Add()
p=doc.Content.Paragraphs.Add()
p.Range.Text="hello world!"

# p.OutlineLevel=1#设置大纲级别
# p.CharacterUnitFirstLineIndent=10#设置第一行或悬挂缩进的值(以字符为单位)
# p.CharacterUnitLeftIndent=10#设置段落缩进,左侧的值
# p.CharacterUnitRightIndent=5#设置段落缩进,右侧的值
# p.OutlineLevel=2
# p.Format.Style.Font.size=20
# p.Format.Style.Font.name="宋体"
# p.Format.Style.Font.Bold=True
# p.Format.Style.Font.Color=13434828

#要设置此属性,请指定样式的本地名称,整数,
# WdBuiltinStyle常量或表示样式的对象。
# p.Style="标题 2"
p.Style=-3
p.Range.InsertParagraphAfter()
for i in range(len(doc.Paragraphs)):
    para = doc.Paragraphs[i]
    print (para.Range.text)
    print(para.Style, type(para.Style))

https://docs.microsoft.com/en-us/dotnet/api/microsoft.office.interop.word.paragraphs.style?view=word-pia

from win32com.client import Dispatch
import win32com.client

# coding=utf-8
import win32com
from win32com.client import Dispatch, DispatchEx

wordApp = Dispatch('Word.Application')  # 打开word应用程序
# word = DispatchEx('Word.Application') #启动独立的进程
wordApp.Visible = 1  # 后台运行,不显示
wordApp.DisplayAlerts = 0  # 不警告
path = r"C:\Users\admin\Desktop\demo.docx"  # word文件路径
doc = wordApp.Documents.Open(FileName=path, Encoding='gbk')
print('----------------')
print ('段落数: ', doc.Paragraphs.count)
# for item in doc.InlineShapes:
# #     print(item.Creator)
#     item.Height=200
# doc.InlineShapes(2).Height=100
print(doc.InlineShapes(2).Height)
print(doc.Shapes.Count)

'''
第一种:是Shape对象(Word中自带的“自选图形”)
第二种:是InlineShape对象(嵌入式图片,也就是所谓
的通过点击菜单栏中的“插入”->“图片”->“来自文件”'''

# doc.Close()  # 关闭word文档
# word.Quit  #关闭word程序
选择图片

 

转载于:https://www.cnblogs.com/Mengchangxin/p/10072632.html

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值