Need Python sample code for open,modify and save the existing excel sheet
Question posted by: amuven
(Newbie)
on
August 21st, 2008 07:27 PM
Hi All,
I'm new to python I have written very basic and small code and I request to help for the following senario.For my project i want to write a python code which should open an already existing Excel sheet which can contain 2 or 3 datasheets and write data in sheet1(first sheet) alone and should not modify the data in rest of the datasheets and save it.
I have heard that people saying it can be done through pyExcelerator or xlrd or xlwt.Since all these things are new to me .. i really don't know how to do it .. :-(
So, I request you all to help me with sample code which will do the above mentioned task as early as possible.
Thanks,
Amudha
2
Answers Posted
Hi!!
I am not so new in Python , so here is a sample of a script i use to do something like you described:
( Of course you should change all the variables i use and put your own ,
but since i came up with this after some good research ( mainly in the fields of
Visual Basic... ) , i think its a good place for you to start... )
I hope this will help a bit....
-
from win32com.client import Dispatch
-
-
def Create_Analysis_Page(Name,Job,Phone,Month,Analysin g_Dict,preview=False):
-
-
xlApp = Dispatch ("Excel.Application")
-
xlWb = xlApp.Workbooks.Open ("C:\\Python25\\Misthos.xlsx")
-
xlSht = xlWb.Worksheets (1)
-
-
xlSht.Cells(1,2).Value=str(Name)
-
xlSht.Cells(2,2).Value=str(Job)
-
xlSht.Cells(3,2).Value=int(Phone)
-
xlSht.Cells(5,2).Value=str(Month)
-
-
try:
-
for i in range (9,40):
-
xlSht.Cells(i,2).Value=Analysing_Dict[i-8][0]
-
xlSht.Cells(i,3).Value=Analysing_Dict[i-8][1]
-
xlSht.Cells(i,4).Value=Analysing_Dict[i-8][2]
-
except:
-
pass
-
-
xlSht.Cells(41,4).Value=Analysing_Dict["Totals"][0]
-
xlSht.Cells(42,4).Value=Analysing_Dict["Totals"][1]
-
xlSht.Cells(43,4).Value=Analysing_Dict["Totals"][2]
-
-
#Preview or not....
-
if preview:
-
xlApp.Visible=1
-
xlApp.ActiveWindow.SelectedSheets.PrintPreview()
-
-
else:
-
#Print The Sheet...
-
xlSht.PrintOut() # This is for printing :)
-
xlApp.DisplayAlerts=False # This is for NOT asking to save changes
-
xlApp.Workbooks.Close()
-
xlApp.DisplayAlerts=True # This is for bringing back the default behaviour
-
xlApp.Quit()
-
Elias
Hi,
It works .... thank you so much .. sorry for late reply :-)
|
|
|
What is Bytes?
We are a network of experts and professionals in IT and software development that help one another with answers to tough questions and share insights.
Get the best answers to your questions from over 197,049 network members.
|