python处理word_使用python操作word

有两种方式:

使用win32com

使用docx

1.使用win32com扩展包

只对windows平台有效

代码:

#coding=utf-8

importwin32comfrom win32com.client importDispatch, DispatchEx

word= Dispatch('Word.Application') #打开word应用程序#word = DispatchEx('Word.Application') #启动独立的进程

word.Visible = 0 #后台运行,不显示

word.DisplayAlerts = 0 #不警告

path = 'G:/WorkSpace/Python/tmp/test.docx' #word文件路径

doc = word.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 inrange(len(doc.Paragraphs)):

para=doc.Paragraphs[i]printpara.Range.textprint '-------------------------'

#直接遍历段落

for para indoc.paragraphs:printpara.Range.text#print para #只能用于文档内容全英文的情况

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

2.使用docx扩展包

优点:不依赖操作系统,跨平台

安装:

pip install python-docx

代码:

importdocxdefread_docx(file_name):

doc=docx.Document(file_name)

content= '\n'.join([para.text for para indoc.paragraphs])return content

创建表格

#coding=utf-8

importdocx

doc=docx.Document()

table= doc.add_table(rows=1, cols=3, style='Table Grid') #创建带边框的表格

hdr_cells= table.rows[0].cells #获取第0行所有所有单元格

hdr_cells[0].text = 'Name'hdr_cells[1].text = 'Id'hdr_cells[2].text = 'Desc'

#添加三行数据

data_lines = 3

for i inrange(data_lines):

cells=table.add_row().cells

cells[0].text= 'Name%s' %i

cells[1].text = 'Id%s' %i

cells[2].text = 'Desc%s' %i

rows= 2cols= 4table= doc.add_table(rows=rows, cols=cols)

val= 1

for i inrange(rows):

cells=table.rows[i].cellsfor j inrange(cols):

cells[j].text= str(val * 10)

val+= 1doc.save('tmp.docx')

读取表格

#coding=utf-8

importdocx

doc= docx.Document('tmp.docx')for table in doc.tables: #遍历所有表格

print '----table------'

for row in table.rows: #遍历表格的所有行

#row_str = '\t'.join([cell.text for cell in row.cells]) # 一行数据

#print row_str

for cell inrow.cells:print cell.text, '\t',print

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值