Tuesday, July 17, 2012

Using Python Script to Copy and Merge Excel sheets


Copy C:\temp\Billed\4540991.xls,4563011.xls,4563034.xls,4563036.xls into temp.xls. 
Create a New Sheet named 20120901. Merge all the Other 4 sheets into One. Sort the data.

'''
Created on Jul 12, 2012

@author: Victor
'''
import win32com.client
xl=win32com.client.Dispatch('Excel.Application')
xl.Visible=0

'''Copy sheets'''
filepath='C:\\temp\\Billed\\'
i=1
for file in ['4540991','4563011','4563034','4563036']:
    filename=filepath+file+'.xls'
    if i==1:
        wb=xl.Workbooks.Open("C:\\temp\\Billed\\4540991.xls")
        sh=wb.Worksheets(i)
        sh.Name=file
    else:
        wbt=xl.Workbooks.Open(filename)
        sht=wbt.Worksheets(1)
        sht.Copy (None,wb.Worksheets(i-1))
        wbt.Close()
        sh=wb.Worksheets(i)
        sh.Name=file
    i+=1

shnew=wb.Worksheets.Add(None,wb.Worksheets(i-1))
shnew.Name="20120901"

'''Copy Cells'''
for i in range(1,wb.Worksheets.Count):
    sh=wb.Worksheets(i)
    if i==1:
        startrow=5
    else:
        startrow=6
    sh.Range(sh.Cells(startrow,1),sh.Cells(sh.UsedRange.Rows.Count,sh.UsedRange.Columns.Count)).Copy()
    shnew.Paste(shnew.Cells(shnew.UsedRange.Rows.Count+startrow-5,1))

#shnew.Columns("D:D").Delete()
shnew.UsedRange.WrapText=False
shnew.Columns("A:I").AutoFit()
shnew.Sort.SortFields.Clear()
shnew.Range(shnew.Cells(2,1),shnew.Cells(shnew.UsedRange.Rows.Count,shnew.UsedRange.Columns.Count)).Sort(Key1=shnew.Range("A2"), Order1=1, Key2=shnew.Range("F2"), Order2=1,Key3=shnew.Range("C2"), Order3=1)

wb.SaveAs('C:\\temp\\Billed\\temp.xls')
wb.Close()
xl.Application.Quit()

1 comment:

  1. Do you think you could post a python script that selects & copies certain columns from one workbook and pastes them into another?

    ReplyDelete