Skip to content

Commit ecc5015

Browse files
authored
TYP/CLN: cleanup _openpyxl.py, add type annotation #36021 (#36022)
1 parent 6c3c695 commit ecc5015

File tree

6 files changed

+20
-50
lines changed

6 files changed

+20
-50
lines changed

ci/deps/azure-37-locale_slow.yaml

+1-1
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ dependencies:
1818
- lxml
1919
- matplotlib=3.0.0
2020
- numpy=1.16.*
21-
- openpyxl=2.5.7
21+
- openpyxl=2.6.0
2222
- python-dateutil
2323
- python-blosc
2424
- pytz=2017.3

ci/deps/azure-37-minimum_versions.yaml

+1-1
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ dependencies:
1919
- numba=0.46.0
2020
- numexpr=2.6.8
2121
- numpy=1.16.5
22-
- openpyxl=2.5.7
22+
- openpyxl=2.6.0
2323
- pytables=3.4.4
2424
- python-dateutil=2.7.3
2525
- pytz=2017.3

doc/source/getting_started/install.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -274,7 +274,7 @@ html5lib 1.0.1 HTML parser for read_html (see :ref
274274
lxml 4.3.0 HTML parser for read_html (see :ref:`note <optional_html>`)
275275
matplotlib 2.2.3 Visualization
276276
numba 0.46.0 Alternative execution engine for rolling operations
277-
openpyxl 2.5.7 Reading / writing for xlsx files
277+
openpyxl 2.6.0 Reading / writing for xlsx files
278278
pandas-gbq 0.12.0 Google Big Query access
279279
psycopg2 2.7 PostgreSQL engine for sqlalchemy
280280
pyarrow 0.15.0 Parquet, ORC, and feather reading / writing

doc/source/whatsnew/v1.2.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,7 @@ Optional libraries below the lowest tested version may still work, but are not c
109109
+-----------------+-----------------+---------+
110110
| numba | 0.46.0 | |
111111
+-----------------+-----------------+---------+
112-
| openpyxl | 2.5.7 | |
112+
| openpyxl | 2.6.0 | X |
113113
+-----------------+-----------------+---------+
114114
| pyarrow | 0.15.0 | X |
115115
+-----------------+-----------------+---------+

pandas/io/excel/_openpyxl.py

+16-43
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from typing import List
1+
from typing import TYPE_CHECKING, Dict, List, Optional
22

33
import numpy as np
44

@@ -8,6 +8,9 @@
88
from pandas.io.excel._base import ExcelWriter, _BaseExcelReader
99
from pandas.io.excel._util import _validate_freeze_panes
1010

11+
if TYPE_CHECKING:
12+
from openpyxl.descriptors.serialisable import Serialisable
13+
1114

1215
class _OpenpyxlWriter(ExcelWriter):
1316
engine = "openpyxl"
@@ -22,53 +25,22 @@ def __init__(self, path, engine=None, mode="w", **engine_kwargs):
2225
if self.mode == "a": # Load from existing workbook
2326
from openpyxl import load_workbook
2427

25-
book = load_workbook(self.path)
26-
self.book = book
28+
self.book = load_workbook(self.path)
2729
else:
2830
# Create workbook object with default optimized_write=True.
2931
self.book = Workbook()
3032

3133
if self.book.worksheets:
32-
try:
33-
self.book.remove(self.book.worksheets[0])
34-
except AttributeError:
35-
36-
# compat - for openpyxl <= 2.4
37-
self.book.remove_sheet(self.book.worksheets[0])
34+
self.book.remove(self.book.worksheets[0])
3835

3936
def save(self):
4037
"""
4138
Save workbook to disk.
4239
"""
43-
return self.book.save(self.path)
44-
45-
@classmethod
46-
def _convert_to_style(cls, style_dict):
47-
"""
48-
Converts a style_dict to an openpyxl style object.
49-
50-
Parameters
51-
----------
52-
style_dict : style dictionary to convert
53-
"""
54-
from openpyxl.style import Style
55-
56-
xls_style = Style()
57-
for key, value in style_dict.items():
58-
for nk, nv in value.items():
59-
if key == "borders":
60-
(
61-
xls_style.borders.__getattribute__(nk).__setattr__(
62-
"border_style", nv
63-
)
64-
)
65-
else:
66-
xls_style.__getattribute__(key).__setattr__(nk, nv)
67-
68-
return xls_style
40+
self.book.save(self.path)
6941

7042
@classmethod
71-
def _convert_to_style_kwargs(cls, style_dict):
43+
def _convert_to_style_kwargs(cls, style_dict: dict) -> Dict[str, "Serialisable"]:
7244
"""
7345
Convert a style_dict to a set of kwargs suitable for initializing
7446
or updating-on-copy an openpyxl v2 style object.
@@ -93,7 +65,7 @@ def _convert_to_style_kwargs(cls, style_dict):
9365
"""
9466
_style_key_map = {"borders": "border"}
9567

96-
style_kwargs = {}
68+
style_kwargs: Dict[str, Serialisable] = {}
9769
for k, v in style_dict.items():
9870
if k in _style_key_map:
9971
k = _style_key_map[k]
@@ -404,7 +376,7 @@ def write_cells(
404376
# Write the frame cells using openpyxl.
405377
sheet_name = self._get_sheet_name(sheet_name)
406378

407-
_style_cache = {}
379+
_style_cache: Dict[str, Dict[str, Serialisable]] = {}
408380

409381
if sheet_name in self.sheets:
410382
wks = self.sheets[sheet_name]
@@ -426,7 +398,7 @@ def write_cells(
426398
if fmt:
427399
xcell.number_format = fmt
428400

429-
style_kwargs = {}
401+
style_kwargs: Optional[Dict[str, Serialisable]] = {}
430402
if cell.style:
431403
key = str(cell.style)
432404
style_kwargs = _style_cache.get(key)
@@ -515,16 +487,17 @@ def get_sheet_by_index(self, index: int):
515487

516488
def _convert_cell(self, cell, convert_float: bool) -> Scalar:
517489

518-
# TODO: replace with openpyxl constants
490+
from openpyxl.cell.cell import TYPE_BOOL, TYPE_ERROR, TYPE_NUMERIC
491+
519492
if cell.is_date:
520493
return cell.value
521-
elif cell.data_type == "e":
494+
elif cell.data_type == TYPE_ERROR:
522495
return np.nan
523-
elif cell.data_type == "b":
496+
elif cell.data_type == TYPE_BOOL:
524497
return bool(cell.value)
525498
elif cell.value is None:
526499
return "" # compat with xlrd
527-
elif cell.data_type == "n":
500+
elif cell.data_type == TYPE_NUMERIC:
528501
# GH5394
529502
if convert_float:
530503
val = int(cell.value)

setup.cfg

-3
Original file line numberDiff line numberDiff line change
@@ -217,9 +217,6 @@ check_untyped_defs=False
217217
[mypy-pandas.io.excel._base]
218218
check_untyped_defs=False
219219

220-
[mypy-pandas.io.excel._openpyxl]
221-
check_untyped_defs=False
222-
223220
[mypy-pandas.io.excel._util]
224221
check_untyped_defs=False
225222

0 commit comments

Comments
 (0)