How to transpose datatable?

I have a datatable in which the values in second column needs to be header in the transposed dt and the values from 3rd column onwards needs to be datarow in the transposed dt

1 Like

Hi Sunny,

Please use these methods to transponse datatable in UiPath:

Let me know if it doesn’t work as expected.

@SunnyJha

You can follow the steps

  1. Delete the first column as you dont need usign delete data row
  2. Now use generate datatable activity and pass the string as String.Join(",",dt.AsEnumerable.Select(function(x) x(0).ToString)) and select comma as row separator and check the header box
  3. Delete the column which you want as headers also the second one
  4. Now use for loop with loop on all columns dt.Columns
  5. Now inside use add data row and in the arrayrow property pass String.Join(",",dt.AsEnumerable.Select(function(x) x(currentitem.ColumnName).ToString)) and in datatable pass the generated table in step 2

Cheers

1 Like

Hi @SunnyJha ,

Try as below

Step 1: Read Range

  • Properties:
    • SheetName: “Sheet1” (or your sheet name)
    • Range: “A1”
    • DataTable: originalDT

Step 2: Invoke Code

  • Properties:
    • Code: (Use the VB.Net code provided above)
    • Language: VB.Net
    • Arguments:
      • originalDT: InArgument (Type: System.Data.DataTable)
      • transposedDT: OutArgument (Type: System.Data.DataTable)

Step 3: Write Range

  • Properties:
    • SheetName: “TransposedSheet” (or any desired sheet name)
    • DataTable: transposedDT

Use below code in invoke code :-

’ Inputs: originalDT (DataTable)
’ Outputs: transposedDT (DataTable)
Dim transposedDT As New DataTable

’ Add columns to transposedDT based on the second column of originalDT
For Each row As DataRow In originalDT.Rows
transposedDT.Columns.Add(row(1).ToString())
Next

’ Add rows to transposedDT with data from the third column onwards of originalDT
For colIndex As Integer = 2 To originalDT.Columns.Count - 1
Dim newRow As DataRow = transposedDT.NewRow()
For rowIndex As Integer = 0 To originalDT.Rows.Count - 1
newRow(rowIndex) = originalDT.Rows(rowIndex)(colIndex).ToString()
Next
transposedDT.Rows.Add(newRow)
Next

’ Output transposedDT
transposedDT

Thanks,
Jayesh

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