473,799 Members | 2,988 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Writing to a blank Excel file using Python

28 New Member
Hello,
I posted here before asking a question about reading excel. Now that the reading problem is solved i am having trouble on how to write to an excel file.

This was my code to read the excel file:

Expand|Select|Wrap|Line Numbers
  1. from win32com.client import Dispatch
  2. xlApp = Dispatch ("Excel.Application")
  3. xlWb = xlApp.Workbooks.Open ("c:/fahad/new/file.xls")
  4. xlSht = xlWb.Worksheets (1)
  5. for row in range(200):
  6.   k=k+1
  7.   for col in range(4):
  8.       if col==1:
  9.         num1=xlSht.Cells(k,1).Value
  10.       elif col==2:
  11.         num2=xlSht.Cells(k,2).Value
  12.       elif col==3:
  13.         num3=xlSht.Cells(k,3).Value
  14.       elif col==4:
  15.         num4=xlSht.Cells(k,4).Value
  16.  
now i am trying to write arrays of numbers and text into respective excel rows and columns. i am pretty sure the code is similar to the reading code but am not sure how to do it.
also is there a way in python to see what commands can be used with a library. like i know for example in many applications if you type in ? and press enter it prints out all the different commands and what the do. so is there some sort of similar thing in python that prints out all the different commands that can be used with the excel module.
Thanks
Oct 3 '07 #1
8 10275
bartonc
6,596 Recognized Expert Expert
Hello,
I posted here before asking a question about reading excel. Now that the reading problem is solved i am having trouble on how to write to an excel file.
<snip>

now i am trying to write arrays of numbers and text into respective excel rows and columns. i am pretty sure the code is similar to the reading code but am not sure how to do it.
also is there a way in python to see what commands can be used with a library. like i know for example in many applications if you type in ? and press enter it prints out all the different commands and what the do. so is there some sort of similar thing in python that prints out all the different commands that can be used with the excel module.
Thanks
If you don't know Visual Basic, you can figure out the command to send by recording a macro of the task. Then read the macro text in the macro editor and translate the command to your Python program.
Oct 3 '07 #2
fahadqureshi
28 New Member
recording an excel macro prints this out in visual basic

ActiveCell.Form ulaR1C1 = "5"
Range("A2").Sel ect
ActiveCell.Form ulaR1C1 = "10"
Range("A3").Sel ect
ActiveCell.Form ulaR1C1 = "15"
Range("A4").Sel ect
ActiveCell.Form ulaR1C1 = "20"
Range("B1").Sel ect

so what would be the correct way to call it in python. would i use the
Oct 3 '07 #3
ghostdog74
511 Recognized Expert Contributor
Hello,
I posted here before asking a question about reading excel. Now that the reading problem is solved i am having trouble on how to write to an excel file.

This was my code to read the excel file:

Expand|Select|Wrap|Line Numbers
  1. from win32com.client import Dispatch
  2. xlApp = Dispatch ("Excel.Application")
  3. xlWb = xlApp.Workbooks.Open ("c:/fahad/new/file.xls")
  4. xlSht = xlWb.Worksheets (1)
  5. for row in range(200):
  6.   k=k+1
  7.   for col in range(4):
  8.       if col==1:
  9.         num1=xlSht.Cells(k,1).Value
  10.       elif col==2:
  11.         num2=xlSht.Cells(k,2).Value
  12.       elif col==3:
  13.         num3=xlSht.Cells(k,3).Value
  14.       elif col==4:
  15.         num4=xlSht.Cells(k,4).Value
  16.  
now i am trying to write arrays of numbers and text into respective excel rows and columns. i am pretty sure the code is similar to the reading code but am not sure how to do it.
also is there a way in python to see what commands can be used with a library. like i know for example in many applications if you type in ? and press enter it prints out all the different commands and what the do. so is there some sort of similar thing in python that prints out all the different commands that can be used with the excel module.
Thanks
try inverting the assignment
Expand|Select|Wrap|Line Numbers
  1. num2=xlSht.Cells(k,2).Value
  2.  
could be
Expand|Select|Wrap|Line Numbers
  1. xlSht.Cells(k,2).Value = num2
  2.  
Oct 4 '07 #4
bartonc
6,596 Recognized Expert Expert
try inverting the assignment
Expand|Select|Wrap|Line Numbers
  1. num2=xlSht.Cells(k,2).Value
  2.  
could be
Expand|Select|Wrap|Line Numbers
  1. xlSht.Cells(k,2).Value = num2
  2.  
This is, in fact, correct. Good show, GD. Thanks.
Oct 4 '07 #5
ghostdog74
511 Recognized Expert Contributor
This is, in fact, correct. Good show, GD. Thanks.
just lucky guess though. :)
Oct 4 '07 #6
fahadqureshi
28 New Member
Yep, inverting it did the trick.

This is the code if anyones interested.

Expand|Select|Wrap|Line Numbers
  1. for row in range(loads):
  2.   k=k+1
  3.   for col in range(6):
  4.       if col==1:
  5.         xlSht.Cells(k,1).Value=busname[f]
  6.       elif col==2:
  7.         xlSht.Cells(k,2).Value=busload[f]       
  8.       elif col==3:
  9.         xlSht.Cells(k,3).Value=mainload[f]
  10.       elif col==4:
  11.         xlSht.Cells(k,4).Value=difference[f]
  12.       elif col==5:
  13.         xlSht.Cells(k,5).Value=percent[f]
  14.   f=f+1
  15.  
Thanks again.
Oct 4 '07 #7
rogerlew
15 New Member
Excel has excellent CSV (comma separated values) support and the Python CSV module is standard and pretty easy to use. It might also make your code easier to modify. With your code if you want to insert an entry into column 3 for example you would have to swap a lot of stuff around.

Expand|Select|Wrap|Line Numbers
  1. import csv
  2. fid=open('c:/fahad/new/file.xls','wb')
  3. writer=csv.writer(fid)
  4. for f, load in enumerate(loads):
  5.     writer.writerow([ busname[f],busload[f],mainload[f],difference[f],percent[f] ] )
  6.  
  7. fid.close()
  8.  
Excel will even recognize formulas
Expand|Select|Wrap|Line Numbers
  1. writer.writerow([ busname[f],
  2.                   busload[f],
  3.                   mainload[f],
  4.                   difference[f],
  5.                   percent[f],
  6.                   r'=%g/%g'%(busload[f],mainload[f] ])
  7.  
If loads is a list of dictionaries you could try something like:
Expand|Select|Wrap|Line Numbers
  1. for load in loads:
  2.     writer.writerow([ load['busname'],
  3.                       load['busload'],
  4.                       load['mainload'],
  5.                       load['difference'],
  6.                       load['percent'] ])
  7.  
Which I think is the most pythonic solution.

Just a friendly suggestion,
Roger
Oct 5 '07 #8
bartonc
6,596 Recognized Expert Expert
Very nice, Roger. Thanks.

Then once the .xls file is created one could:
Expand|Select|Wrap|Line Numbers
  1. import os
  2. os.startfile(r'c:/fahad/new/file.xls')
Which (I believe) works with either Excel or OpenOffice.
Oct 5 '07 #9

Sign in to post your reply or Sign up for a free account.

Similar topics

13
35567
by: Allison Bailey | last post by:
Hi Folks, I'm a brand new Python programmer, so please point me in the right direction if this is not the best forum for this question.... I would like to open an existing MS Excel spreadsheet and extract information from specific worksheets and cells. I'm not really sure how to get started with this process. I ran the COM Makepy utility from my PythonWin (IDE from ActiveSTate),
6
2485
by: ÒÊÃÉɽÈË | last post by:
i want to compare the content in excel,but i don't know whick module to use! can you help me?
10
5979
by: Robert Hicks | last post by:
I need to pull data out of Oracle and stuff it into an Excel spreadsheet. What modules have you used to interface with Excel and would you recommend it? Robert
8
5503
by: jquest | last post by:
Hi Again; I have had help from this group before and want to thank everyone, especially PCDatasheet. My database includes a field called HomePhone, it uses the (xxx)xxx-xxx format to include area code. When a customer calls, I currently use Ctrl F with the HomePhone field highlighted. Then I enter the last 4 digits and use the find next option. This is cumbersome, so I have tried several methods (including a macro) using comand...
10
52153
by: Aaron | last post by:
Hello, I have a small application that I need to save data from 7 text boxes in to a csv file. This will entail btnNext_Click function that will create a new csv file and enter the 7 data fields in the csv file; as well, each click on next will return carriage to a new line. Client does not what his data in an Access database(he hates Access with a passion)--he feels more comfortable with Excel. This data will be no greater than 1000...
6
6681
by: AleydisGP | last post by:
I have a .plt file (which is a tab delimited ASCII file) and I want to format it to get a .dbf with data in rows and columns, detele some rows/columns and substitute decimal '.' with ','. All this using Python (I'm using Pythonwin). The .plt file looks like this: * ISCST3 (02035): Tersa * MODELING OPTIONS USED: * CONC URBAN ELEV DFAULT
1
3003
by: =?Utf-8?B?ZmhpbGxpcG8=?= | last post by:
We have a code snippet that downloads data to Excel. it is writing row by row. This causes a performance issue. Any ideas on how to speed this up will be appreciated. Please find below an excerpt of the code: #region Method:WriteToExcel /// <summary> /// <para>Description : Method is used to Write the records into excel</para>
15
9442
by: patf | last post by:
Hi - experienced programmer but this is my first Python program. This URL will retrieve an excel spreadsheet containing (that day's) msci stock index returns. http://www.mscibarra.com/webapp/indexperf/excel?priceLevel=0&scope=0&currency=15&style=C&size=36&market=1897&asOf=Jul+25%2C+2008&export=Excel_IEIPerfRegional Want to write python to download and save the file. So far I've arrived at this:
20
3580
by: Marin Brkic | last post by:
Hello all, please, let me apologize in advance. English is not my first language (not even my second one), so excuse any errors with which I'm about to embarass myself in front of the general public. Second, I'm relatively new to python, so sorry if this seems like a stupid question. I'm trying to find a way to write data to excel cells (or to be more specific to an .xls file), let's say for the sake of argument, data readen from a...
0
9686
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10475
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10250
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10026
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9068
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7564
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6805
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5585
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3757
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.