我编写 python 脚本来编辑 MS Office Word 文档。在 Word 中打开 .docx 文件时,编辑 .docx 文件对我来说非常重要。Python 必须改变它。我使用 python 库 docx 来做到这一点。代码工作正常,但在 MS Word 中打开时无法编辑 ms-word 文档。我得到错误
PermissionError: [Errno 13] Permission denied: 'demo.docx'
为了解决这个问题,我尝试了这篇文章中推荐的所有内容:
PermissionError: [Errno 13] 权限被拒绝
没有任何帮助。我总是收到错误:
PermissionError: [Errno 13] Permission denied: 'demo.docx'
Python代码无关紧要,但我也在这里发布(代码有效,问题在于权限):
from docx import Document
from docx.shared import Inches
import traceback
try:
document = Document()
document.add_heading('Document Title', 0)
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(
'first 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')
)
table = document.add_table(rows=1, cols=3)
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 in records:
row_cells = table.add_row().cells
row_cells[0].text = str(qty)
row_cells[1].text = id
row_cells[2].text = desc
document.add_page_break()
document.save('demo.docx')
except:
traceback.print_exc()
如评论中所述,您无法修改已使用其他应用程序(即:python-docx
模块)打开的 Word 文档。
但是,您可以使用win32api / pywin32直接访问 Word(与 Excel 相同)。
您可以使用类似的语法(仅转换为 Python)使用 VBA 执行您可以执行的所有操作。
它又重又丑,但至少它有效。
这是此博客中的代码示例:https : //www.blog.pythonlibrary.org/2010/07/16/python-and-microsoft-office-using-pywin32/
import win32com.client as win32
RANGE = range(3, 8)
def edit_word():
word = win32.gencache.EnsureDispatch('Word.Application')
doc = word.Documents.Add()
word.Visible = True
rng = doc.Range(0,0)
rng.InsertAfter('Hacking Word with Python\r\n\r\n')
sleep(1)
for i in RANGE:
rng.InsertAfter('Line %d\r\n' % i)
sleep(1)
rng.InsertAfter("\r\nPython rules!\r\n")
doc.Close(False)
word.Application.Quit()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句