Writing Data to Excel Sheets using C# Invoke Code

I processed some variables which in the Invoke Code activity.
I want to write these down in an excel sheet.

Is there any way to do this in the Invoke Code activity?

I can’t write it down using OpenRPA activities because each of the variables I’m getting is through a loop - so I can’t pass the variable (through updating OpenRPA variable) to the OpenRPA workspace.

Is there any workaround?

Hi @Quamrul_Zabedin
I think yes… there is a way to write data to an Excel sheet using the Invoke Code activity. You can make use of the Microsoft Office Interop libraries to interact with Excel.

Here’s a basic example of how you can achieve what you ask:

using Excel = Microsoft.Office.Interop.Excel;

// Create a new instance of Excel application
Excel.Application excelApp = new Excel.Application();

// Open an existing workbook or create a new one
Excel.Workbook workbook = excelApp.Workbooks.Add();

// Get the active worksheet
Excel.Worksheet worksheet = workbook.ActiveSheet;

// Set the column headers in cells A1 and B1.
worksheet.Cells[1, "A"] = "Variable 1";
worksheet.Cells[1, "B"] = "Variable 2";
// ... Add more headers if needed

// Initialize row counter
int row = 2; //or 1 

// Loop through your variables and write them to Excel
foreach (var variable in yourVariables)
{
    worksheet.Cells[row, "A"] = variable.Variable1;
    worksheet.Cells[row, "B"] = variable.Variable2;
    // ... Write more variables if needed

    row++;
}

// Save the workbook
workbook.SaveAs("path/to/your/file.xlsx");

// Close Excel and release resources
workbook.Close();
excelApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);

Make sure to replace "path/to/your/file.xlsx" with the actual path where you want to save the Excel file.
Keep in mind that using the Excel Interop libraries requires having Microsoft Excel installed on the machine where the OpenRPA process is running and remember to install “Microsoft.Office.Interop.Excel” via Nuget in OpenRPA Package Manager and add it in the “imports” panel.

I didn’t test this idea yet but hopefully it can help you. Follow this link for more info:

Or maybe some one else here you might have a better idea.

2 Likes

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.