阅读工作簿中的excel表格并写入单词

问题描述 投票:0回答:1

我正在尝试使用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:
  Local\Programs\Python\Python38-32\lib\site-packages\win32com\client\dynamic.py", line 527, in __getattr__
    raise AttributeError("%s.%s" % (self._username_, attr))
AttributeError: Open.sheet_names

请帮助我解决此问题

python win32com
1个回答
0
投票

您可以尝试以下。

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://docs.microsoft.com/en-us/dotnet/api/microsoft.office.interop.word.document
range = doc.Content  # Or, range = doc.Range()

# Doc for Excel.Workbook Interface: https://docs.microsoft.com/en-us/dotnet/api/microsoft.office.interop.excel.workbook
# Sheets property here: https://docs.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://docs.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://docs.microsoft.com/en-us/dotnet/api/microsoft.office.interop.word.range.pasteexceltable

您可以在以下链接上引用文档。

字:https://docs.microsoft.com/en-us/dotnet/api/microsoft.office.interop.word

Excel:https://docs.microsoft.com/en-us/dotnet/api/microsoft.office.interop.excel

© www.soinside.com 2019 - 2024. All rights reserved.