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