Convert CSV file to Excel

This script converts CSV file (Windmill will receive it as base64 string) into an Excel file format.

Script windmill

by henri186 ยท 4/17/2024

  • Submitted by henri186 Python3
    Created 755 days ago
    1
    import base64
    2
    from io import BytesIO
    3
    import pandas as pd
    4
    from io import StringIO
    5
    import openpyxl
    6
    
    
    7
    def main(csv_bytes: bytes) -> str:
    8
        # Convert bytes to string
    9
        csv_string = csv_bytes.decode('utf-8')
    10
        
    11
        # Use StringIO to convert string to a file-like object for reading into DataFrame
    12
        csv_file = StringIO(csv_string)
    13
        
    14
        # Read CSV data into DataFrame
    15
        df = pd.read_csv(csv_file)
    16
        
    17
        # Convert DataFrame to Excel and save to a BytesIO object
    18
        excel_buffer = BytesIO()
    19
        df.to_excel(excel_buffer, index=False)
    20
        excel_buffer.seek(0)  # Rewind the buffer to the beginning
    21
        
    22
        # Encode the Excel file into a base64 string
    23
        base64_excel = base64.b64encode(excel_buffer.read()).decode('utf-8')
    24
    
    
    25
        return { "file": { "content": base64_excel, "filename": "data.xlsx" } }