Spaces:
Sleeping
Sleeping
import openpyxl | |
import os | |
class ExcelAutomator: | |
def __init__(self, name: list, output: str): | |
self.columns = name | |
self.output = output if output.endswith(".xlsx") else f"{output}.xlsx" | |
if os.path.exists(self.output): | |
self.workbook = openpyxl.load_workbook(self.output) | |
self.sheet = self.workbook.active | |
else: | |
self.workbook = openpyxl.Workbook() | |
self.sheet = self.workbook.active | |
for col_num, column_name in enumerate(self.columns, 1): | |
self.sheet.cell(row=1, column=col_num, value=column_name) | |
def save(self, data_dict): | |
""" | |
Save a new row of data to the Excel file. | |
:param data_dict: Dictionary with keys as column names and values as the data to save. | |
""" | |
row_data = [data_dict.get(column, None) for column in self.columns] | |
self.sheet.append(row_data) | |
def save_to_file(self): | |
""" | |
Save the workbook to a file. | |
""" | |
self.workbook.save(self.output) | |
return self.output | |