【问题标题】:pywin32 excel to word overwrite issuepywin32 excel to word覆盖问题
【发布时间】:2013-09-02 10:21:00
【问题描述】:

以下是我的代码,我同时使用 pywin32 和 xlrd。这里的问题是我的 xls 有多个工作表,并且工作表被逐个访问并写入 word 文档,当代码写入 word 文档时,它会覆盖前一个工作表的内容。我正在寻求的是我需要一一附加我的数据。如果有人能提供解决方案,我将不胜感激,因为我需要它来解决我正在解决的问题:

from win32com import client
import xlrd
book1 = xlrd.open_workbook("E:/excel2word/454184_Appendix E 300713 Worcester NH.xls",formatting_info=True)
excel = client.Dispatch("Excel.Application")
word = client.Dispatch("Word.Application")
doc = word.Documents.Open("E:/excel2word/Doc1.docx")
book = excel.Workbooks.Open("E:/excel2word/454184_Appendix E 300713 Worcester NH.xls")
count = book.Sheets.Count
print count
mapping ={'1':'A','2':'B','3':'C','4':'D','5':'E','6':'F','7':'G','8':'H','9':'I','10':'J','11':'K'}
for i in xrange(1,count+1):
    sh = book1.sheet_by_index(i-1)
    sheet = book.Worksheets(i)
    print sheet
    sheet.Range("A4:"+str(mapping[str(sh.ncols)])+""+str(sh.nrows)).Copy()
    print "A4:"+str(mapping[str(sh.ncols)])+""+str(sh.nrows)
    doc.Content.PasteExcelTable(False,False,False)

【问题讨论】:

  • 你为什么要同时读取带有 xlrd 和 COM 的 excel 文件?当你这样做时,你的 PasteExcelTable 会覆盖之前的 PasteExcelTable?
  • 是的,它会覆盖上一个表。楼主有解决办法吗?

标签: python excel com ms-word pywin32


【解决方案1】:

我在这里遇到了同样的问题。 经过大量搜索,我终于有了解决方案...... 您需要使用 Range.Collapse 和 Range.MoveEnd

range1 = doc.Range()
range1.Collapse(0)
range1.MoveEnd()
range1.PasteExcelTable(False,False,False)

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多