簡體   English   中英

使用 Python win32com 獲取 Excel 工作表列表

[英]Using Python win32com to get list of Excel worksheets

尋找一種簡單的方法來獲取 Excel 工作簿中的工作表列表,使用 Python 中的 win32com 3. 我寧願避免迭代,但找不到 ZC1C425268E68385D1AB507

  • 調用工作簿的.Sheets屬性,返回一個Sheets集合, <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.
    • 要獲取每張工作表的名稱,必須使用.Name方法
  • 如下圖,可以通過列表推導輕松獲取sheet_names
  • 或者,您可以使用以下方式獲取工作表對象字典
    • ws = {f'ws{i}': wb.Sheets(sheet.Name) for i, sheet in enumerate(wb.Sheets)}
    • 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

設置和 function 調用

# 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')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM