我已经安装了
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
?
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"]