Repository: OpenBB-finance/OpenBBTerminal
File: openbb_terminal/helper_funcs.py (Python)

Code before:
                regex=True,
            )

            df = df.applymap(revert_lambda_long_number_format)

            if exp_type.endswith("csv"):
                df.to_csv(saved_path)
            elif exp_type.endswith("json"):
                df.reset_index(drop=True, inplace=True)
                df.to_json(saved_path)
            elif exp_type.endswith("xlsx"):
                # since xlsx does not support datetimes with timezones we need to remove it
                df = remove_timezone_from_dataframe(df)

                if sheet_name is None:  # noqa: SIM223
                    df.to_excel(
                        saved_path,
                        index=True,
                        header=True,
                    )

                elif saved_path.exists():
                    # Load the Excel file to get the existing data
                    existing_df = pd.read_excel(saved_path, sheet_name=sheet_name)
                    # Get the number of rows in the existing data
                    start_row = (
                        existing_df.shape[0] + 1
                    )  # Add 1 to start writing after the last row

                    # Append data to the existing sheet
                    with pd.ExcelWriter(
                        saved_path,
                        mode="a",
                        if_sheet_exists="overlay",
                        engine="openpyxl",
                    ) as writer:
                        df.to_excel(
                            writer,
                            sheet_name=sheet_name,
                            startrow=start_row,
                            index=True,
                            header=False,
                        )

                else:
                    with pd.ExcelWriter(
                        saved_path,
                        engine="openpyxl",
                    ) as writer:
                        df.to_excel(
                            writer, sheet_name=sheet_name, index=True, header=True

Review comment (suggestion):
Thanks for this! It appears to be working, however with one slight caveat:

- Assigning a sheet name to a new export is now generating an error:

```
(🦋) /stocks/ $ load aapl -i 1 --source YahooFinance --export test1.xlsx --sheet-name regular

Loading Intraday 1min data for AAPL with starting period 2023-09-26.
Error: Worksheet named 'regular' not found
```

IIUC, the solution is looking to read for an existing sheet name.  We just need to add in something that writes to a new sheet name if the supplied name does not exist in the file.

Code after:
    func_name : str
        Name of the command that invokes this function
    df : pd.Dataframe
        Dataframe of data to save
    sheet_name : str
        If provided.  The name of the sheet to save in excel file
    figure : Optional[OpenBBFigure]
        Figure object to save as image file
    margin : bool
        Automatically adjust subplot parameters to give specified padding.
    """

    if export_type:
        saved_path = compose_export_path(func_name, dir_path).resolve()
        saved_path.parent.mkdir(parents=True, exist_ok=True)
        for exp_type in export_type.split(","):
            # In this scenario the path was provided, e.g. --export pt.csv, pt.jpg
            if "." in exp_type:
                saved_path = saved_path.with_name(exp_type)
            # In this scenario we use the default filename
            else:
                if ".OpenBB_openbb_terminal" in saved_path.name:
                    saved_path = saved_path.with_name(
                        saved_path.name.replace(
                            ".OpenBB_openbb_terminal", "OpenBBTerminal"
                        )
                    )
                saved_path = saved_path.with_suffix(f".{exp_type}")

            exists, overwrite = False, False
            is_xlsx = exp_type.endswith("xlsx")
            if sheet_name is None and is_xlsx or not is_xlsx:
                exists, overwrite = ask_file_overwrite(saved_path)

            if exists and not overwrite:
                existing = len(list(saved_path.parent.glob(saved_path.stem + "*")))
                saved_path = saved_path.with_stem(f"{saved_path.stem}_{existing + 1}")

            df = df.replace(
                {
                    r"\[yellow\]": "",
                    r"\[/yellow\]": "",
                    r"\[green\]": "",
                    r"\[/green\]": "",
                    r"\[red\]": "",
                    r"\[/red\]": "",
                    r"\[magenta\]": "",
                    r"\[/magenta\]": "",
                },
                regex=True,
            )