对单元格范围进行排序,win32com.client [英] Sort a Range of Cells, win32com.client

查看:531
本文介绍了对单元格范围进行排序,win32com.client的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用win32com在python中对一系列单元格进行排序:

I am trying to sort a range of cells in python using win32com:

我一直在使用的代码是:

Code I've been using is:

sheet.Range("A1:B8").Sort(Key1=sheet.Range("B1"), Orientation=constants.xlAscending)

正在工作.它按第二列对单元格范围进行排序:

which is working. It sorts the range of cells by the second column:

在需要时,将降序"而不是升序"排序:

When I want, is to sort Descending instead of Ascending:

sheet.Range("B8:A1").Sort(Key1=sheet.Range("B1"), Orientation=constants.xlDescending)

但是出于某些奇怪的原因,它会切换每列中的数据,并且不对第二列中最初的值进行排序.

but for some weird reason, it switches the data from each column and doesn't sort the values that were initially in the second column.

我玩过许多不同类型的参数,所以使用了排序方法

I've played with a ton of different parameters types sot the sort method here but nothing seems to work. Has anyone have experience with this method and can suggest how I would get the second column sort descending?

推荐答案

您的方向参数应为:xlSortColumns = 1xlSortRows = 2.请参阅下面的Python脚本调整.如 Range.Sort方法所示, Order1 Order2 Order3 接受xlAscending = 1xlDescending = 2值.

Your orientation argument should either be: xlSortColumns = 1 or xlSortRows = 2. See below Python script adjustment. As the Range.Sort Method shows, Order1, Order2, and Order3 takes the xlAscending = 1 or xlDescending = 2 values.

import win32com.client

wbk = 'C:\\Path\\To\\Workbook.xlsx'

xlApp = win32com.client.Dispatch("Excel.Application")
xlApp.Workbooks.Open(wbk)

xlAscending = 1
xlSortColumns = 1    
xlApp.Sheets(1).Columns("A:B").Sort(Key1=xlApp.Sheets(1).Range("B1"),
                                    Order1=xlAscending, Orientation=xlSortColumns)

xlApp.Quit
xlApp = None                                 

这篇关于对单元格范围进行排序,win32com.client的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆