Excel Manipulation using Python

Tim Golden mail at timgolden.me.uk
Fri Apr 18 11:36:43 EDT 2008


Krishna wrote:
> I was trying to delete rows in an existing .xls file using python. How
> do I do that? I was using the following code, it seem to work if I
> type in python window, but if I save it in text editor and drage and
> drop the .py file, it doesnt work. What am I doing wrong here?  Thanks
> for your help!
> 
> import win32com.client
> from time import sleep
> excel = win32com.client.Dispatch("Excel.Application")
> 
> def Extract():
>  	excel.Visible = 0
> 	workbook=excel.Workbooks.Open('C:\Trial.xls')
> 
> 	i=1
> 	for n in range(1,10):
> 		excel.Rows(i).Select
> 		excel.Selection.Delete
> 		excel.Selection.Delete
> 		i=i+2
> 		workbook.Save()
> 		print "saved"
> 
> 	excel.Quit()

Several points worthy of note:

1) When you're dealing with Windows filenames, either make
the strings raw -- Open (r"c:\trial.txt") -- or use the other
slashes =-- Open ("c:/trial.xls").

2) You're not actually calling the Select and Delete
methods, merely referencing them. Try .Delete () etc.

3) You're saving the workbook every time round the loop,
but perhaps you knew that. Might prompt you everytime
as you're overwriting, but again, maybe you knew...

TJG



More information about the Python-list mailing list