from openpyxl import load_workbook,Workbook
import csv,os
import pandas as pd

class SaveCsv():
    def __init__(self, folder_path:str,sheets:dict,flag_create_folder=False):
        '''
        sheets {"sheet_name":[列1,列2,列3]}
        '''
        self.folder_path = folder_path
        if flag_create_folder:
            self.create_folder(folder_path)
        self.sheets=sheets
        for sheet_name in self.sheets:
            self.write_header(sheet_name)

    @staticmethod
    def create_folder(folder_path):
        os.makedirs(folder_path, exist_ok=True)

    def get_filename(self,sheet_name):
        return f"{self.folder_path}/{sheet_name}.csv"
    
    def write_header(self,sheet_name):
        # 打开CSV文件并写入数据
        with open(self.get_filename(sheet_name), mode='w', newline='', encoding='utf-8') as file:
            fieldnames = self.sheets[sheet_name]
            writer = csv.DictWriter(file, fieldnames=fieldnames)
            # 写入表头
            writer.writeheader()

    def read_to_df(self,sheet_name):
        df = pd.read_csv(self.get_filename(sheet_name))
        return df
        

    def append_data_stale(self,sheet_name,new_rows):
        '''
        new_row: 要添加的新数据 (以dataframe形式)
        '''

        df = pd.read_excel(self.file_path, sheet_name=sheet_name)
        new_df = pd.concat([df, new_rows], join='outer', ignore_index=True)

        new_df.to_excel(self.file_path, sheet_name=sheet_name, index=False)

    def append_data(self,sheet_name,new_rows):
        # 加载Excel文件
        workbook = Workbook()
        # load_workbook(filename=self.file_path)

        # 选择指定的工作表
        if sheet_name in workbook.sheetnames:
            sheet = workbook[sheet_name]
        else:
            print(f"工作表 '{sheet_name}' 不存在！")
            exit()

        # 修改指定单元格的值
        sheet['A1'] = '新的值'  # 修改A1单元格的值

        # 保存更改
        workbook.save(filename=self.file_path)


    def set_cell(self,sheet_name,row, col_name,value):
        df = pd.read_excel(self.file_path, sheet_name=sheet_name)
        df.loc[row, col_name] = value

        # 将修改后的 DataFrame 写回 Excel 文件
        df.to_excel(self.file_path, sheet_name=sheet_name, index=False)