File size: 1,452 Bytes
021d91d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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"