Skip to content

Commit

Permalink
fix(openpyxl): handle import bug when excel backend openpyxl not inst…
Browse files Browse the repository at this point in the history
…alled
  • Loading branch information
sqr00t committed Feb 2, 2024
1 parent 7f49328 commit e277289
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 8 deletions.
23 changes: 15 additions & 8 deletions nesta_ds_utils/loading_saving/S3.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from nesta_ds_utils.loading_saving import file_ops

from nesta_ds_utils.loading_saving.gis_interface import _gis_enabled
from nesta_ds_utils.loading_saving import _excel_backend_available

if _gis_enabled:
from nesta_ds_utils.loading_saving.gis_interface import (
Expand Down Expand Up @@ -53,10 +54,13 @@ def _df_to_fileobj(df_data: pd.DataFrame, path_to: str, **kwargs) -> io.BytesIO:
df_data.to_csv(buffer, **kwargs)
elif fnmatch(path_to, "*.parquet"):
df_data.to_parquet(buffer, **kwargs)
elif fnmatch(path_to, "*.xlsx"):
df_data.to_excel(buffer, **kwargs)
elif fnmatch(path_to, "*.xlsm"):
df_data.to_excel(buffer, **kwargs)
elif fnmatch(path_to, "*.xlsx") or fnmatch(path_to, "*.xlsm"):
if _excel_backend_available:
df_data.to_excel(buffer, **kwargs)
else:
raise ModuleNotFoundError(
"Please install 'io_extras' extra from nesta_ds_utils or 'openpyxl' to upload excel files."
)
else:
raise NotImplementedError(
"Uploading dataframe currently supported only for 'csv', 'parquet', 'xlsx' and xlsm'."
Expand Down Expand Up @@ -258,10 +262,13 @@ def _fileobj_to_df(fileobj: io.BytesIO, path_from: str, **kwargs) -> pd.DataFram
return pd.read_csv(fileobj, **kwargs)
elif fnmatch(path_from, "*.parquet"):
return pd.read_parquet(fileobj, **kwargs)
elif fnmatch(path_from, "*.xlsx"):
return pd.read_excel(fileobj, **kwargs)
elif fnmatch(path_from, "*.xlsm"):
return pd.read_excel(fileobj, **kwargs)
elif fnmatch(path_from, "*.xlsx") or fnmatch(path_from, "*.xlsm"):
if _excel_backend_available:
return pd.read_excel(fileobj, **kwargs)
else:
raise ModuleNotFoundError(
"Please install 'io_extras' extra from nesta_ds_utils or 'openpyxl' to download excel files."
)


def _fileobj_to_dict(fileobj: io.BytesIO, path_from: str, **kwargs) -> dict:
Expand Down
7 changes: 7 additions & 0 deletions nesta_ds_utils/loading_saving/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
try:
import openpyxl

_excel_backend_available = True

except ImportError:
_excel_backend_available = False

0 comments on commit e277289

Please sign in to comment.