Spaces:
Sleeping
Sleeping
| import pandas as pd | |
| import io | |
| from datetime import datetime | |
| def flatten_multiindex_columns(df): | |
| """ | |
| Chuyển đổi MultiIndex columns thành cột đơn để xuất Excel | |
| Args: | |
| df: DataFrame có MultiIndex columns | |
| Returns: | |
| DataFrame với cột đã được làm phẳng | |
| """ | |
| if isinstance(df.columns, pd.MultiIndex): | |
| df = df.copy() | |
| df.columns = [f"{col[0]}_{col[1]}" if col[1] else col[0] for col in df.columns] | |
| return df | |
| def to_excel(dataframes, sheet_names): | |
| """ | |
| Xuất nhiều DataFrame ra file Excel | |
| Args: | |
| dataframes: List các DataFrame | |
| sheet_names: List tên sheet tương ứng | |
| Returns: | |
| BytesIO chứa dữ liệu Excel | |
| """ | |
| output = io.BytesIO() | |
| with pd.ExcelWriter(output, engine='xlsxwriter') as writer: | |
| for df, sheet_name in zip(dataframes, sheet_names): | |
| # Flatten MultiIndex columns trước khi xuất | |
| df_flattened = flatten_multiindex_columns(df) | |
| df_flattened.to_excel(writer, sheet_name=sheet_name, index=False) | |
| output.seek(0) | |
| return output | |
| def generate_excel_filename(symbol): | |
| """ | |
| Tạo tên file Excel với mã cổ phiếu và ngày hiện tại | |
| Args: | |
| symbol: Mã cổ phiếu | |
| Returns: | |
| Tên file Excel | |
| """ | |
| return f"{symbol}_financial_report_{datetime.now().strftime('%Y%m%d')}.xlsx" |