Using Python win32com to get list of Excel worksheets

末鹿安然 提交于 2020-06-29 03:42:23

问题


Looking for a simple way to get a list of the worksheets in an Excel workbook using win32com in Python 3. I would prefer to avoid iterating, but can't find a function to do so.


回答1:


  • Callig the .Sheets property of the workbook, returns a Sheets collection, <win32com.gen_py.Microsoft Excel 16.0 Object Library.Sheets instance at 0x1597583762504>
    • In order to get each sheet, you must iterate, which returns an object, <win32com.gen_py.Microsoft Excel 16.0 Object Library._Worksheet instance at 0x1597583219080> for each sheet.
    • To get the name of each sheet, you must use the .Name method
  • As shown below, you can easily get sheet_names with a list comprehension
  • Alternative, you can get a dictionary of worksheet objects with
    • ws = {f'ws{i}': wb.Sheets(sheet.Name) for i, sheet in enumerate(wb.Sheets)}
    • Assign a value with ws['ws0'].Range('A1').Value = 1

Function

import win32com.client as win32
from pathlib import Path
import sys

win32c = win32.constants

def run_excel(f_path: Path, f_name: str) -> list:

    filename = f_path / f_name

    # create excel object
    excel = win32.gencache.EnsureDispatch('Excel.Application')

    # excel can be visible or not
    excel.Visible = True  # False
    
    # try except for file / path
    try:
        wb = excel.Workbooks.Open(filename)
    except com_error as e:
        if e.excepinfo[5] == -2146827284:
            print(f'Failed to open spreadsheet.  Invalid filename or location: {filename}')
        else:
            raise e
        sys.exit(1)

    # get worksheet names        
    sheet_names = [sheet.Name for sheet in wb.Sheets]
        
    wb.Close(True)
    excel.Quit()
        
    return sheet_names

Setup and function call

# file path
f_path = Path.cwd()  # file in current working directory
# f_path = Path(r'c:\...\Documents')  # file located somewhere else

# excel file
f_name = 'test.xlsx'

# function call
run_excel(f_path, f_name)

# output
['Sheet1', 'Sheet2', 'Sheet3', 'Sheet4']

# create a worksheet object
ws1 = wb.Sheets('Sheet1')
  • How to create a pivot table in Excel with python win32com
  • Automate Excel with Python
    • Examples with Pivot Table
  • Excel VBA reference
  • Workbook object (Excel)
  • Worksheet object (Excel)


来源:https://stackoverflow.com/questions/62505403/using-python-win32com-to-get-list-of-excel-worksheets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!