Order Col when processing and create output

I have an Excel file and a data table that I need to add to it. However, the table’s columns don’t directly match those in the Excel file, so they need to be reordered. For example, column E of the data table needs to be placed in column B of the Excel file, and so on for other columns.

How can I do this?

1 Like

@Sowjanya_N1

you can rearrange the columns in datatable if you know the order of the excel columns

dt = dt.DefaultView.ToTable({"Col1","Col2"},False)

Col1,Col2 etc are the columns you can add all columns in the order you need

cheers

Hii @Sowjanya_N1

Create a new DataTable with columns arranged in the same order as the Excel file. Then populate this table from the original DataTable by mapping columns to the required positions, for example taking column E into column B, and so on. After reordering in memory, write the new DataTable to Excel using a single Write Range.

you can use the following expression with column names in order you need

use assign with

dt = dt.DefaultView.ToTable(false,{“Col1”,“Col2”,“Col3”})

{“Col1”,“Col2,Col3”} - here you can specify the column names you need and in the order you need so that the columns are re arranged in datatable

You can below linq as well.

dt = dt.AsEnumerable().
Select(Function(r) New Object(){r(“ColE”), r(“ColA”), r(“ColC”)}).
CopyToDataTable()

Mark as solution if it helps.

1 Like

Why we have to use false parameter.

ToTable(distinct As Boolean, ParamArray columnNames As String())
False means keeps all rows, including duplicates
True means returns only distinct rows based on the selected columns

3 Likes

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