espin086 / espin086/AppGenie

Make is so all sheets are read in even hidden sheets

Open
#2 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
Python
Stars
1
Forks
1
PR merge metrics
No merged PRs in 30d

Description

Sure! I'll provide a new `ExcelHandler` implementation that includes a function to read all sheets, including hidden ones. I'll follow your requirements and make sure to add docstrings, logging, argparse for command-line arguments, and follow the Black formatting standard.

Additionally, I'll include a sequence diagram to illustrate how the ExcelHandler class works.

### ExcelHandler Code

```python
import pandas as pd
import logging
import argparse
from openpyxl import load_workbook

# Configure logging
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")

class ExcelHandler:
"""
Class to handle Excel files, including reading and writing sheets,
and handling hidden sheets.
"""

def __init__(self, file_path):
"""
Initialize the ExcelHandler.

Args:
file_path (str): Path to the Excel file.
"""
self.file_path = file_path
self.dataframes = {}
self.logger = logging.getLogger(__name__)

def read_sheet(self, sheet_name):
"""
Read a specific sheet from the Excel file.

Args:
sheet_name (str): Name of the sheet to read.

Returns:
DataFrame: DataFrame containing the sheet data.
"""
try:
df = pd.read_excel(self.file_path, sheet_name=sheet_name)
self.dataframes[sheet_name] = df
self.logger.info(f"Read sheet '{sheet_name}' successfully.")
return df
except Exception as e:
self.logger.error(f"Error reading sheet {sheet_name}: {e}")

def read_all_sheets(self):
"""
Read all sheets, including hidden ones, from the Excel file.

Returns:
dict: Dictionary with sheet names as keys and DataFrames as values.
"""
try:
wb = load_workbook(self.file_path)
for sheet_name in wb.sheetnames:
df = pd.read_excel(self.file_path, sheet_name=sheet_name)
self.dataframes[sheet_name] = df
self.logger.info("Read all sheets (including hidden) successfully.")
return self.dataframes
except Exception as e:
self.logger.error(f"Error reading all sheets: {e}")

def save_sheet(self, df, sheet_name):
"""
Save a DataFrame to a specific sheet in the Excel file.

Args:
df (DataFrame): DataFrame to save.
sheet_name (str): Name of the sheet to save the DataFrame to.
"""
try:
with pd.ExcelWriter(self.file_path, engine="openpyxl", mode="a", if_sheet_exists="replace") as writer:
df.to_excel(writer, sheet_name=sheet_name, index=False)
self.dataframes[sheet_name] = df
self.logger.info(f"Saved sheet '{sheet_name}' successfully.")
except Exception as e:
self.logger.error(f"Error saving sheet {sheet_name}: {e}")

def save_all_sheets(self):
"""
Save all DataFrames in the dataframes dictionary to the Excel file.
"""
try:
with pd.ExcelWriter(self.file_path, engine="openpyxl") as writer:
for sheet_name, df in self.dataframes.items():
df.to_excel(writer, sheet_name=sheet_name, index=False)
self.logger.info("Saved all sheets successfully.")
except Exception as e:
self.logger.error(f"Error saving all sheets: {e}")

def get_dataframe(self, sheet_name):
"""
Get the DataFrame of a specific sheet.

Args:
sheet_name (str): Name of the sheet to get the DataFrame for.

Returns:
DataFrame: DataFrame containing the sheet data.
"""
return self.dataframes.get(sheet_name, None)

def list_sheets(self):
"""
List all sheet names in the Excel file, including hidden ones.

Returns:
list: List of sheet names.
"""
try:
wb = load_workbook(self.file_path)
sheet_names = wb.sheetnames
self.logger.info("Listed all sheets (including hidden) successfully.")
return sheet_names
except Exception as e:
self.logger.error(f"Error listing sheets: {e}")
return []

def main():
parser = argparse.ArgumentParser(description="Excel Handler with hidden sheet support")
parser.add_argument("file_path", type=str, help="Path to the Excel file")
args = parser.parse_args()

# Initialize ExcelHandler
excel_handler = ExcelHandler(args.file_path)

# Read all sheets
sheets = excel_handler.read_all_sheets()
print("Sheets:", sheets)

# List all sheets
sheet_names = excel_handler.list_sheets()
print("Sheet Names:", sheet_names)

# Save all sheets back to the Excel file
for sheet_name, df in sheets.items():
excel_handler.save_sheet(df, sheet_name)
excel_handler.save_all_sheets()

if __name__ == "__main__":
main()

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.