Python *** 作Word

Python *** 作Word,第1张

概述Python *** 作Word使用python *** 作word 有两种方式:使用win32com使用docx 1.使用win32com扩展包只对windows平台有效# coding=utf-8import win32comfrom win32com.client import Dispatch, DispatchExword = Dispatch('Word.Application')  # 打开word应用程序#

Python *** 作Word

使用python *** 作word  

有两种方式:

使用win32com使用docx

 

1.使用win32com扩展包

只对windows平台有效

# Coding=utf-8import win32comfrom win32com.clIEnt import dispatch, dispatchExword = 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 in range(len(doc.Paragraphs)):    para = doc.Paragraphs[i]    print para.Range.textprint '-------------------------'# 直接遍历段落for para in doc.paragraphs:    print para.Range.text    # print para  #只能用于文档内容全英文的情况doc.Close()  # 关闭word文档# word.Quit  #关闭word程序

 

2.使用docx扩展包

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

安装:

pip install python-docx

参考文档:  https://python-docx.readthedocs.io/en/latest/index.html

代码:

import docxdef read_docx(file_name):    doc = docx.document(file_name)    content = '\n'.join([para.text for para in doc.paragraphs])    return content


创建表格

# Coding=utf-8import docxdoc = 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 = 3for i in range(data_lines):    cells = table.add_row().cells    cells[0].text = 'name%s' % i    cells[1].text = 'ID%s' % i    cells[2].text = 'Desc%s' % irows = 2cols = 4table = doc.add_table(rows=rows, cols=cols)val = 1for i in range(rows):    cells = table.rows[i].cells    for j in range(cols):        cells[j].text = str(val * 10)        val += 1doc.save('tmp.docx')

读取表格

# Coding=utf-8import docxdoc = 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 in row.cells:            print cell.text, '\t',        print


 相关样式参考:  https://python-docx.readthedocs.io/en/latest/user/styles-understanding.html


使用PYTHON编辑和读取WORD文档

python调用word接口主要用到的模板为python-docx,基本 *** 作官方文档有说明。

python-docx官方文档地址

使用python新建一个word文档, *** 作就像文档里介绍的那样:

from docx import documentfrom docx.shared import Inchesdocument = document()document.add_heading('document Title', 0)  #插入标题p = document.add_paragraph('A plain paragraph having some ')   #插入段落p.add_run('bold').bold = Truep.add_run(' and some ')p.add_run('italic.').italic = Truedocument.add_heading('heading, level 1', level=1)document.add_paragraph('Intense quote', style='IntenseQuote')document.add_paragraph(    'first item in unordered List', style='ListBullet')document.add_paragraph(    'first item in ordered List', style='ListNumber')document.add_picture('monty-truth.png', wIDth=Inches(1.25)) #插入图片table = document.add_table(rows=1, cols=3) #插入表格hdr_cells = table.rows[0].cellshdr_cells[0].text = 'Qty'hdr_cells[1].text = 'ID'hdr_cells[2].text = 'Desc'for item in recordset:    row_cells = table.add_row().cells    row_cells[0].text = str(item.qty)    row_cells[1].text = str(item.ID)    row_cells[2].text = item.descdocument.add_page_break()document.save('demo.docx')  #保存文档

读取和编辑一个已有的word文档,只需在一开始添加上文件路径就行了,如下:

from docx import documentfrom docx.shared import Inchesdocument = document('demo.docx')  #打开文件demo.docxfor paragraph in document.paragraphs:    print(paragraph.text)  #打印各段落内容文本document.add_paragraph(    'Add new paragraph', style='ListNumber')    #添加新段落document.save('demo.docx') #保存文档

如果是想读取其中的图片或是更复杂地编辑,首先我们需要先来认识下docx文档的格式组成:

docx是Microsoft Office2007之后版本使用的,用新的基于XML的压缩文件格式取代了其目前专有的默认文件格式,在传统的文件名扩展名后面添加了字母“x”(即“.docx”取代“.doc”、“.xlsx”取代“.xls”、“.pptx”取代“.ppt”)。

docx格式的文件本质上是一个ZIP文件。将一个docx文件的后缀改为ZIP后是可以用解压工具打开或是解压的。事实上,Word2007的基本文件就是ZIP格式的,他可以算作是docx文件的容器。

docx 格式文件的主要内容是保存为XML格式的,但文件并非直接保存于磁盘。它是保存在一个ZIP文件中,然后取扩展名为docx。将.docx 格式的文件后缀改为ZIP后解压, 可以看到解压出来的文件夹中有word这样一个文件夹,它包含了Word文档的大部分内容。而其中的document.xml文件则包含了文档的主要文本内容。

word目录下:

document.xml文件内容:

media目录下存放word文档中插入的图片:

所以,我们可以使用手工的方法编辑文件document.xml来对该word文档内容进行编辑,或是提取文档media中图片文件的方式来提取该word文档中所插入的所有图片。

import zipfile  f=zipfile.Zipfile('demo.docx','r')   for filename in f.nameList():     f.extract(filename)





About Me

........................................................................................................................

● 本文作者:小麦苗,部分内容整理自网络,若有侵权请联系小麦苗删除

● 本文在itpub( http://blog.itpub.net/26736162 )、博客园( http://www.cnblogs.com/lhrbest )和个人weixin公众号( xiaomaimiaolhr )上有同步更新

● 本文itpub地址: http://blog.itpub.net/26736162

● 本文博客园地址: http://www.cnblogs.com/lhrbest

● 本文pdf版、个人简介及小麦苗云盘地址: http://blog.itpub.net/26736162/viewspace-1624453/

● 数据库笔试面试题库及解答: http://blog.itpub.net/26736162/viewspace-2134706/

● DBA宝典今日头条号地址: http://www.toutiao.com/c/user/6401772890/#mid=1564638659405826

........................................................................................................................

● QQ群号: 230161599 (满) 、618766405

● weixin群:可加我weixin,我拉大家进群,非诚勿扰

● 联系我请加QQ好友 ( 646634621 ) ,注明添加缘由

● 于 2019-01-01 06:00 ~ 2019-01-31 24:00 在魔都完成

● 最新修改时间:2019-01-01 06:00 ~ 2019-01-31 24:00

● 文章内容来源于小麦苗的学习笔记,部分整理自网络,若有侵权或不当之处还请谅解

● 版权所有,欢迎分享本文,转载请保留出处

........................................................................................................................

● 小麦苗的微店 : https://weidian.com/s/793741433?wfr=c&ifr=shopdetail

● 小麦苗出版的数据库类丛书 : http://blog.itpub.net/26736162/viewspace-2142121/

● 小麦苗OCP、OCM、高可用网络班 : http://blog.itpub.net/26736162/viewspace-2148098/

● 小麦苗腾讯课堂主页 : https://lhr.ke.qq.com/

........................................................................................................................

使用 weixin客户端 扫描下面的二维码来关注小麦苗的weixin公众号( xiaomaimiaolhr )及QQ群(DBA宝典)、添加小麦苗weixin, 学习最实用的数据库技术。

........................................................................................................................

 

 




来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/26736162/vIEwspace-2375245/,如需转载,请注明出处,否则将追究法律责任。

总结

以上是内存溢出为你收集整理的Python *** 作Word全部内容,希望文章能够帮你解决Python *** 作Word所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/langs/1187583.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-03
下一篇2022-06-03

发表评论

登录后才能评论

评论列表(0条)

    保存