RPA / Robocorp

Convert format / Excel

Convert from CSV to Excel

tasks.py
Copied!

import pandas as pd
from robocorp.tasks import task
import os

@task
def convert_csv_to_excel():
    """Convert a CSV file to Excel format."""
    # Path to the input CSV file
    csv_path = "input/data.csv"

    # Path for the output Excel file
    excel_path = "output/data.xlsx"

    # Ensure the output directory exists
    os.makedirs(os.path.dirname(excel_path), exist_ok=True)

    # Read CSV file
    print(f"Reading CSV file: {csv_path}")
    df = pd.read_csv(csv_path)

    # Display data summary
    print(f"CSV file contains {len(df)} rows and {len(df.columns)} columns")
    print(f"Column names: {', '.join(df.columns)}")

    # Save as Excel file
    print(f"Converting to Excel and saving to: {excel_path}")
    df.to_excel(excel_path, index=False)

    print("Conversion completed successfully!")

Convert from Excel to CSV

tasks.py
Copied!

import pandas as pd
from robocorp.tasks import task
import os

@task
def convert_excel_to_csv():
    """Convert an Excel file to CSV format."""
    # Path to the input Excel file
    excel_path = "input/data.xlsx"

    # Path for the output CSV file
    csv_path = "output/data.csv"

    # Ensure the output directory exists
    os.makedirs(os.path.dirname(csv_path), exist_ok=True)

    # Read Excel file
    print(f"Reading Excel file: {excel_path}")
    df = pd.read_excel(excel_path)

    # Display data summary
    print(f"Excel file contains {len(df)} rows and {len(df.columns)} columns")
    print(f"Column names: {', '.join(df.columns)}")

    # Save as CSV file
    print(f"Converting to CSV and saving to: {csv_path}")
    df.to_csv(csv_path, index=False)

    print("Conversion completed successfully!")

Convert from Excel to PDF

tasks.py
Copied!

from robocorp.tasks import task
from RPA.Excel.Application import Application
import os

@task
def convert_excel_to_pdf():
    """Convert an Excel file to PDF format."""
    # Path to the input Excel file (use absolute path for Excel application)
    excel_path = os.path.abspath("input/report.xlsx")

    # Path for the output PDF file
    pdf_path = os.path.abspath("output/report.pdf")

    # Ensure the output directory exists
    os.makedirs(os.path.dirname(pdf_path), exist_ok=True)

    # Initialize Excel application
    excel = Application()

    try:
        # Open Excel application and the file
        print(f"Opening Excel file: {excel_path}")
        excel.open_application()
        excel.open_workbook(excel_path)

        # Export as PDF
        print(f"Converting to PDF and saving to: {pdf_path}")
        excel.export_as_pdf(pdf_path)

        print("Conversion completed successfully!")

    finally:
        # Make sure to close Excel application
        excel.close_document(save=False)  # Don't save since we're just converting
        excel.quit_application()