我正在尝试使用python读取excelworkbook中的每一张表,并写入现有的word文档。
代码剪切如下:
from win32com import client
excel = client.Dispatch("Excel.Application")
word = client.Dispatch("Word.Application")
doc = word.Documents.Open("D:/xx.docx")
xl = excel.Workbooks.Open("D:/yy.xlsx")
for i in xl.sheet_names:
xl_sheet = xl_workbook.sheet_by_name(sheet_names[i])
xl.Range("A1:D20").Copy()
但是,遇到错误:
for i in xl.sheet_names:
LocalProgramsPythonPython38-32libsite-packageswin32comclientdynamic.py", line 527, in __getattr__
raise AttributeError("%s.%s" % (self._username_, attr))
AttributeError: Open.sheet_names
请帮助我解决这个问题
您可以尝试以下操作。
from win32com import client
# If you want to use client.constants, you should use client.gencache.EnsureDispatch instead of client.Dispatch
word = client.gencache.EnsureDispatch("Word.Application")
excel = client.gencache.EnsureDispatch("Excel.Application")
doc = word.Documents.Open("D:/xx.docx")
wb = excel.Workbooks.Open("D:/yy.xlsx")
# If you set Visible = True, it is easier to check if things are going right.
word.Visible = True
excel.Visible = True
# Doc for Word.Document interface: https://learn.microsoft.com/en-us/dotnet/api/microsoft.office.interop.word.document
range = doc.Content # Or, range = doc.Range()
# Doc for Excel.Workbook Interface: https://learn.microsoft.com/en-us/dotnet/api/microsoft.office.interop.excel.workbook
# Sheets property here: https://learn.microsoft.com/en-us/dotnet/api/microsoft.office.interop.excel.workbook#microsoft-office-interop-excel--workbook-sheets
for ws in wb.Sheets:
# Doc for Word.Range.Collapse method: https://learn.microsoft.com/en-us/dotnet/api/microsoft.office.interop.word.range.collapse
range.Collapse(client.constants.wdCollapseEnd)
ws.Range("A1:D20").Copy()
range.Paste() # There is also PasteExcelTable method. Check the doc: https://learn.microsoft.com/en-us/dotnet/api/microsoft.office.interop.word.range.pasteexceltable
您可以参考以下链接上的文档。
单词:https://learn.microsoft.com/en-us/dotnet/api/microsoft.office.interop.word
Excel:https://learn.microsoft.com/en-us/dotnet/api/microsoft.office.interop.excel