我正在尝试使用 Excel 对象的 win32com python api 对 Excel 中的一系列行进行分组。我似乎无法让它发挥作用。我的代码如下:
excel = win32com.client.gencache.EnsureDispatch("Excel.Application")
excel.Workbooks.Open(r"pathtomyexcel.xlsx")
excel.Visible = True
book = excel.ActiveWorkbook
sheet = book.Worksheets("Test")
sheet.Activate()
# trying to get a range of rows using various methods.
# Using cell ranges
sheet.Range(sheet.Cells(6, 1),sheet.Cells(15,1)).Group
# Using row ranges
sheet.Range(sheet.Rows(6), sheet.Rows(15)).Rows.Group
# Using the rows range method
sheet.Rows("6:15").Group
我找到了this帖子,但答案并不明确,如评论中所述。看起来 group 方法需要一个范围对象,但是我上面的测试只是没有做任何事情。也没有发生任何错误。
供参考,我使用的是 python 2.7 和 Excel 2010
在深入挖掘并拼凑出一些线索后,我在 Stack 上找到了这些线索并使用了 VBA API 参考库我找到了解决方案。
import win32com.client
# Set the excel object
excel = win32com.client.gencache.EnsureDispatch("Excel.Application")
# Open an excel document
excel.Workbooks.Open(r"pathtomyexcel.xlsx")
# Make the excel document visible
excel.Visible = True
# Set a variavle to grab the active workbook
book = excel.ActiveWorkbook
# Set a variable to the specific work sheet
sheet = book.Worksheets("Test")
# Activate the sheet. Note, you must activate the sheet you are
# working in, before the Select() method will work
sheet.Activate()
# Select the range of rows you want to group.
# In this case, I selected a range by cell indices and used the
# EntireRow method to select the entire rows of the range
# Need to call the Select method using parentheses () while using
# the win32com python api, whereas the VBA call doesn't require the parentheses.
sheet.Range(sheet.Cells(6, 1), sheet.Cells(15, 1)).EntireRow.Select()
# Need to set the Group() method on the current selection in the
# excel object, which is the selection made in the previous line
excel.Selection.Group()
# Bonus code to collapse the grouped rows
sheet.Outline.ShowLevels(RowLevels=1)
提供的代码已在 Python 3.11 + Excel 365 上测试。它应该可以在您的环境中正常运行。
# Using cell ranges
sheet.Range(sheet.Cells(6, 1),sheet.Cells(15,1)).EntireRow.Rows.Group()
# Using row ranges
sheet.Range(sheet.Rows(1), sheet.Rows(3)).Rows.Group()
# Using the rows range method
sheet.Rows("20:25").Rows.Group()
# Using A1 reference
sheet.Range("A40:A45").EntireRow.Rows.Group()