How to complete a series of Excel operations such as read range, write range, etc., using coded automation in UiPath?


I want to implement a series of Excel operations in coded automation(coded workflow). Do you have experience in this area? Thank you!

Why do you want to go for coded automation ?? You already have all the excel related activities right?

I just want use coded automation to complete excel-related operations, rather than drag the excel actvities.

Ways to get started:

Example one:
var dt = new DataTable();
var readWorkbook = new UiPath.Excel.Activities.ReadRange();
readWorkbook.WorkbookPath = @“C:\Temp\temp.xlsx”;
readWorkbook.SheetName = “Sheet1”;
readWorkbook.AddHeaders = true;
readWorkbook.PreserveFormat = true;
readWorkbook.DataTable = new System.Activities.OutArgument<System.Data.DataTable>(context => dt);
WorkflowInvoker.Invoke(readWorkbook);

Example Two:
System.Data.DataTable dtOutput = new();
WorkflowInvoker.Invoke(
new UiPath.Excel.Activities.ReadRange
{
WorkbookPath = @“C:\Temp\temp.xlsx”,
SheetName = “Sheet1”,
AddHeaders = true,
PreserveFormat = false,
DataTable = new OutArgument(ctx => dtOutput)
});

Example Three:
var result = WorkflowInvoker.Invoke(
new UiPath.Excel.Activities.ReadRange
{
WorkbookPath = @“C:\Temp\temp.xlsx”,
SheetName = “Sheet1”,
AddHeaders = true,
PreserveFormat = true,
});
var dtOutput2 = result[“DataTable”] as System.Data.DataTable;

FYI - when getting an error like

                            System.Activities.InvalidWorkflowException: 
                            'The following errors were encountered while processing the workflow tree:
                            'Literal<UiElement>': Literal only supports value types and the immutable type System.String.
                            The type UiPath.Core.UiElement cannot be used as a literal.'
                            
                            then use an args dictionary like below for the arg causing the error
                            
                            var args = new Dictionary<string, object>
                                            {
                                                { "InUiElement", eleForClick },
                                            };
                            WorkflowInvoker.Invoke(new NClick
                                {
                                OutUiElement = new OutArgument<UiElement>(ctx => ele_out_ClickedElement),
                                ClickType = bln_in_DoubleClick ? NClickType.Double : NClickType.Single,
                                MouseButton = NMouseButton.Left,
                                CursorMotionType = CursorMotionType.Instant,  
                                InteractionMode = NChildInteractionMode.HardwareEvents,  
                                ActivateBefore = true,  
                                KeyModifiers = NKeyModifiers.None
                                },args);