如何键入注释工作表,或更具体地说,只读工作表?

问题描述 投票:0回答:1

我已经安装了

types-openpyxl

我以只读模式加载工作簿,然后从中访问工作表:

import openpyxl as xl

excel_file = Path("./xl.xlsx")
wb: xl.Workbook = xl.load_workbook(excel_file, read_only=True, data_only=True, keep_links=False)
ws = wb["hello world"]

如何输入注释

ws

python openpyxl mypy python-typing
1个回答
0
投票

在运行时,

Workbook.__getitem__()
返回
Worksheet
ReadOnlyWorksheet
WriteOnlyWorksheet
Chartsheet

ws
最精确的类型是:

from openpyxl.chartsheet.chartsheet import Chartsheet
from openpyxl.worksheet.worksheet import Worksheet
from openpyxl.worksheet._read_only import ReadOnlyWorksheet
from openpyxl.worksheet._write_only import WriteOnlyWorksheet

ws: Worksheet | ReadOnlyWorksheet | WriteOnlyWorksheet | ChartSheet

这也反映在存根中,使用以下仅类型检查时间符号:

class _WorksheetLike(Worksheet, WriteOnlyWorksheet, ReadOnlyWorksheet): ...
class _WorksheetOrChartsheetLike(Chartsheet, _WorksheetLike): ...
class Workbook:
    ...
    def __getitem__(self, key: str) -> _WorksheetOrChartsheetLike: ...

就您而言,既然您有

read_only=True
,您可能只需要
ReadOnlyWorksheet
:

from openpyxl.worksheet._read_only import ReadOnlyWorksheet

ws: ReadOnlyWorksheet = wb["hello world"]
© www.soinside.com 2019 - 2024. All rights reserved.