Excel Manipulation using Python

K

Krishna

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()
 
T

Tim Golden

Krishna said:
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
 
K

Krishna

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- Hide quoted text -

- Show quoted text -

Cool, That worked! Thanks for your help TJG!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top