【问题标题】:Read excel sheets in workbook and write to word阅读工作簿中的 excel 表并写入 word
【发布时间】:2023-03-15 13:46:01
【问题描述】:

我正在尝试使用 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】:

您可以尝试以下方法。

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

【讨论】:

  • 谢谢。它解决了问题。 Excel中的格式可以复制到Word中吗?使用上述 python 代码从 Excel 复制后的 word 格式发生变化。
  • @user13487681 你是说表格格式?然后,您可以使用range.Paste() 右侧评论中提到的Range.PasteExcelTable 方法。你可以试试range.PasteExcelTable(False, False, True) 而不是range.Paste()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多