Solved

Python win32com Excel - How to sort?

Posted on 2014-07-25
10
1,440 Views
Last Modified: 2014-07-28
Hi

In Python, I am looking to drive  Excel with win32com ..

Seems straight forward ..but I do not know how to do a two column sort.

So, with this little code snippet that addes in some data, how would I select a5:d9 and sort on column A, and Column B?

import win32com.client as win32

# Load excel:
excel = win32.gencache.EnsureDispatch('Excel.Application')
excel.Visible = True
wb = excel.Workbooks.Add()
ws = wb.Worksheets('Sheet1')
ws.Name = 'Sort Data'

# Add data:
ws.Cells(5,1).Value = "Dallas"
ws.Cells(5,2).Value = "Amy"
ws.Cells(5,3).Value = 12
ws.Cells(5,4).Value = 2450.99

ws.Cells(6,1).Value = "New York"
ws.Cells(6,2).Value = "Allen"
ws.Cells(6,3).Value = 69
ws.Cells(6,4).Value = 2182.50

ws.Cells(7,1).Value = "Atlanta"
ws.Cells(7,2).Value = "Bobby"
ws.Cells(7,3).Value = 122
ws.Cells(7,4).Value = 124.44

ws.Cells(8,1).Value = "New York"
ws.Cells(8,2).Value = "Julie"
ws.Cells(8,3).Value = 28
ws.Cells(8,4).Value = 375.00

ws.Cells(9,1).Value = "Dallas"
ws.Cells(9,2).Value = "David"
ws.Cells(9,3).Value = 67
ws.Cells(9,4).Value = 3002.25

# Sort ????

Open in new window


Please help!

Thx Scott
0
Comment
Question by:srbarker8
  • 8
  • 2
10 Comments
 
LVL 45

Expert Comment

by:aikimark
ID: 40221394
For better performance
1. suspend screen updating
excel.screenupdating = False
#your worksheet populating or processing statements here
excel.screenupdating = True

2. You should be able to assign an entire set (row) of cell values at a time.  For that matter, you should be able to assign an entire 2D (array) range of values in a single operation.  Although my article uses VBA as the code examples, it should work in Python
Fast Data Push to Excel:  http:A_2253.html

You can specify up to three columns in a sort operation.  If more than three columns, you would need to iterate the columns, in least-to-most significant order.  I will post a two-column example.
0
 
LVL 45

Expert Comment

by:aikimark
ID: 40221410
This is how I would invoke the sort method in VBA.  Now I need to translate these optional (and named) parameters into Python.
ws.Cells(1, 1).CurrentRegion.Sort key1:=ws.Cells(1, 1), key2:=ws.Cells(1, 2), header:=2

Open in new window

0
 
LVL 45

Expert Comment

by:aikimark
ID: 40221417
Please try this:
ws.Cells(1, 1).CurrentRegion.Sort(key1=ws.Cells(1, 1), key2=ws.Cells(1, 2), header=2)

Open in new window

0
Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

 
LVL 45

Expert Comment

by:aikimark
ID: 40221448
I think this might be the way to write the row-at-a-time push of data
excel.screenupdating = False
rng = wb.Worksheets('Sheet1').range('A1:D1')
rng.value = ["Dallas", "Amy", 12, 2450.99]
rng.Offset(1).value = ["New York", "Allen", 69, 2182.50]
rng.Offset(2).value = ["Atlanta", "Bobby", 122, 124.440]
rng.Offset(3).value = ["New York", "Julie", 28, 375.00]
rng.Offset(4).value = ["Dallas", "David", 67, 3002.25]
excel.screenupdating = True

Open in new window

0
 
LVL 45

Expert Comment

by:aikimark
ID: 40222887
I tested this syntax:
import win32com.client as win32
# Load excel:
excel = win32.gencache.EnsureDispatch('Excel.Application')
excel.Visible = True
wb = excel.Workbooks.Add()
ws = wb.Worksheets('Sheet1');
ws.Name = 'Sort Data'

excel.ScreenUpdating = False
rng = ws.Range('A1:D1');
rng.Value = ["Dallas", "Amy", 12, 2450.99]
rng.GetOffset(1).Value = ["New York", "Allen", 69, 2182.50]
rng.GetOffset(2).Value = ["Atlanta", "Bobby", 122, 124.440]
rng.GetOffset(3).Value = ["New York", "Julie", 28, 375.00]
rng.GetOffset(4).Value = ["Dallas", "David", 67, 3002.25]
excel.ScreenUpdating = True

Open in new window

0
 

Author Comment

by:srbarker8
ID: 40224632
Hi there,

Thanks for working on this...

I tried this line as you suggested but the translation is failing on the parameters..

error messageAny suggestions?
0
 
LVL 45

Expert Comment

by:aikimark
ID: 40224646
Try capitalizing the first letter of the parameter names.  I found that the win32com interface to the Excel objects, methods, and properties is case sensitive.
0
 
LVL 45

Accepted Solution

by:
aikimark earned 500 total points
ID: 40224704
Here is a script that works.  I had to add the orientation parameter to the sort to get it to sort 'properly'
import win32com.client as win32
# Load excel:   or gencache.EnsureDispatch
excel = win32.Dispatch('Excel.Application')
excel.Visible = True
wb = excel.Workbooks.Add()
ws = wb.Worksheets('Sheet1');
ws.Name = 'Sort Data'

excel.ScreenUpdating = False
rng = ws.Range('A1:D1');
rng.Value = ["Dallas", "Amy", 12, 2450.99]
rng.GetOffset(1).Value = ["New York", "Allen", 69, 2182.50]
rng.GetOffset(2).Value = ["Atlanta", "Bobby", 122, 124.440]
rng.GetOffset(3).Value = ["New York", "Julie", 28, 375.00]
rng.GetOffset(4).Value = ["Dallas", "David", 67, 3002.25]
rc = ws.Cells(1, 1).CurrentRegion.Sort(Key1=ws.Cells(1, 1), Key2=ws.Cells(1, 2), Header=2, Orientation=1)
excel.ScreenUpdating = True

Open in new window

0
 
LVL 45

Expert Comment

by:aikimark
ID: 40224742
Here is an example of pushing all the data into Excel in one operation.  Notice that the target range is five rows tall, enough to hold all the data.
import win32com.client as win32
# Load excel:   or gencache.EnsureDispatch
excel = win32.Dispatch('Excel.Application')
excel.Visible = True
wb = excel.Workbooks.Add()
ws = wb.Worksheets('Sheet1');
ws.Name = 'Sort Data'

excel.ScreenUpdating = False
rng = ws.Range('A1:D5');
rng.Value = (["Dallas", "Amy", 12, 2450.99], ["New York", "Allen", 69, 2182.50],
             ["Atlanta", "Bobby", 122, 124.440], ["New York", "Julie", 28, 375.00],
             ["Dallas", "David", 67, 3002.25])
rc = ws.Cells(1, 1).CurrentRegion.Sort(Key1=ws.Cells(1, 1), Key2=ws.Cells(1, 2), Header=2, Orientation=1)
excel.ScreenUpdating = True

Open in new window

0
 

Author Closing Comment

by:srbarker8
ID: 40224746
Thx a lot!
0

Featured Post

Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Less strange, but still introduction This introduction was added (1st August, 2011) to reflect some reactions.  Firstly, the term basics in the title of the article...  As any other word, it is a symbol with meaning attached to the word by some a…
Flask is a microframework for Python based on Werkzeug and Jinja 2. This requires you to have a good understanding of Python 2.7. Lets install Flask! To install Flask you can use a python repository for libraries tool called pip. Download this f…
Learn the basics of lists in Python. Lists, as their name suggests, are a means for ordering and storing values. : Lists are declared using brackets; for example: t = [1, 2, 3]: Lists may contain a mix of data types; for example: t = ['string', 1, T…
Learn the basics of if, else, and elif statements in Python 2.7. Use "if" statements to test a specified condition.: The structure of an if statement is as follows: (CODE) Use "else" statements to allow the execution of an alternative, if the …

774 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question