forked from richard512/python-Excel-Automation
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcopyPaste.py
More file actions
40 lines (32 loc) · 1.09 KB
/
copyPaste.py
File metadata and controls
40 lines (32 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
'''
Copies A2:C4 from worksheet1.xlsx to new row(s) starting at the end of worksheet2.xlsx, then saves it as worksheet3.xlsx
'''
from win32com.client import Dispatch
wkbk1 = "worksheet1.xlsx"
wkbk2 = "worksheet2.xlsx"
wkbk3 = "worksheet3.csv"
excel = Dispatch("Excel.Application")
excel.Visible = 1
excel.ScreenUpdating = False
# copy from source
source = excel.Workbooks.Open(wkbk1)
excel.Range("A2:D4").Select()
excel.Selection.Copy()
# paste (appended) to target
target = excel.Workbooks.Open(wkbk2)
ws = target.sheets(1)
used = ws.UsedRange
maxrow = used.Row + used.Rows.Count - 1
maxcol = used.Column + used.Columns.Count - 1
newrow = maxrow + 1
destrange = "A"+str(newrow) #+":C9"
print(destrange)
excel.Range(destrange).Select()
excel.Selection.PasteSpecial(Paste=-4122)
# Excel requires the user to press enter after paste()
# It says "select destination and press enter or choose paste"
# This simulates pressing of the enter key:
shell = Dispatch("WScript.Shell")
shell.SendKeys("{ENTER}", 0)
excel.ScreenUpdating = True
ws.SaveAs(wkbk3, 24) # 24 = csv format