def copy_table_from_excel_to_word():
import time
from win32com import client
excel = client.Dispatch('Excel.Application')
word = client.Dispatch('Word.Application')
doc = word.Documents.Open('C:\\Users\\Administrator\\Desktop\\test.docx')
wb = excel.Workbooks.Open('C:\\Users\\Administrator\\Desktop\\tav.xlsx')
sheet = wb.Worksheets(1)
tn = sheet.Cells(2, 1).value
start_row = 2
end_row = 2
# 循環 把Excel第一列值一樣的選中復制到word中
while True:
if sheet.Cells(start_row, 1).value = '':
print('finish')
break
if sheet.Cells(end_row + 1, 1).value == tn:
end_row += 1
else:
print(tn)
word.Selection.InsertAfter('\n%s\n' % tn)
word.Selection.InsertAfter('%s\n' % sheet.Cells(start_row, 2).value)
time.sleep(0.3)
_ = word.Selection.MoveRight()
time.sleep(0.3)
_ = sheet.Range('C1:H1').Copy()
word.Selection.PasteExcelTable(False, True, False)
time.sleep(0.3)
_ = sheet.Range('C%d:H%d' % (start_row, end_row)).Copy()
word.Selection.PasteExcelTable(False, True, False)
time.sleep(0.3)
start_row = end_row + 1
end_row += 1
tn = sheet.Cells(start_row, 1).value
doc.Close()
wb.Close()
com對象的各種屬性和方法參考:
https://docs.microsoft.com/zh-CN/office/vba/api/word.paragraphformat
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
