doc文件所占用空间更小。docx格式的文件本质上是一个ZIP文件,所以其实也可以把.docx文件直接改成.zip,解压后,里面的
word/document.xml包含了Word文档的大部分内容,图片文件则保存在word/media里面。
python-docx不支持.doc文件,间接解决方法是在代码里面先把.doc转为.docx。
一、安装包
pip3 install python-docx
二、创建word文档
下面是在官文示例基础上对个别地方稍微修改,并加上函数的使用说明
from docx importDocumentfrom docx.shared importInches
document=Document()#添加标题,并设置级别,范围:0 至 9,默认为1
document.add_heading('Document Title', 0)#添加段落,文本可以包含制表符(\t)、换行符(\n)或回车符(\r)等
p = document.add_paragraph('A plain paragraph having some')#在段落后面追加文本,并可设置样式
p.add_run('bold').bold =True
p.add_run('and some')
p.add_run('italic.').italic =True
document.add_heading('Heading, level 1', level=1)
document.add_paragraph('Intense quote', style='Intense Quote')#添加项目列表(前面一个小圆点)
document.add_paragraph('first item in unordered list', style='List Bullet')
document.add_paragraph('second item in unordered list', style='List Bullet')#添加项目列表(前面数字)
document.add_paragraph('first item in ordered list', style='List Number')
document.add_paragraph('second item in ordered list', style='List Number')#添加图片
document.add_picture('monty-truth.png', width=Inches(1.25))
records=(
(3, '101', 'Spam'),
(7, '422', 'Eggs'),
(4, '631', 'Spam, spam, eggs, and spam')
)#添加表格:一行三列#表格样式参数可选:#Normal Table#Table Grid#Light Shading、 Light Shading Accent 1 至 Light Shading Accent 6#Light List、Light List Accent 1 至 Light List Accent 6#Light Grid、Light Grid Accent 1 至 Light Grid Accent 6#太多了其它省略...
table = document.add_table(rows=1, cols=3, style='Light Shading Accent 2')#获取第一行的单元格列表
hdr_cells =table.rows[0].cells#下面三行设置上面第一行的三个单元格的文本值
hdr_cells[0].text = 'Qty'hdr_cells[1].text = 'Id'hdr_cells[2].text = 'Desc'
for qty, id, desc inrecords:#表格添加行,并返回行所在的单元格列表
row_cells =table.add_row().cells
row_cells[0].text=str(qty)
row_cells[1].text =id
doc
查看了网上的各种方法,大部分还是接受将doc文件强制另存为docx文件(使用代码转换,而不是直接修改后缀),在读取即可,需要另外安装win32com模块,注意就是直接使用 pip install win32com 安装不成功,需要用
python -m pip install pypiwin32
即可,简单使用如下
import docx
import win32com.client as wc
#doc文件另存为docx
word = wc.Dispatch("Word.Application")
doc = word.Documents.Open(r"F:\\***\\***\\append\\***.doc")
#上面的地方只能使用完整绝对地址,相对地址找不到文件,且,只能用“\\”,不能用“/”,哪怕加了 r 也不行,涉及到将反斜杠看成转义字符。
doc.SaveAs(r"F:\\***\\***\\appendDoc\\***.docx", 12, False, "", True, "", False, False, False, False)#转换后的文件,12代表转换后为docx文件
#doc.SaveAs(r"F:\\***\\***\\appendDoc\\***.docx", 12)#或直接简写
#注意SaveAs会打开保存后的文件,有时可能看不到,但后台一定是打开的
doc.Close
word.Quit
path = "appendDoc/***.docx"
file = docx.Document(path)
for p in file.paragraphs:
print(p.text)