Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving a column in a datatable from first to last

I have a sql stored procedure that returns a certain group of columns in my datatable.
How can I move (let's say) the column in the first position, to the last position before I export the datatable to excel ?

Dim myConn As New SqlConnection(strConnection)
Dim myCmd As New SqlCommand(strSQL, myConn)
Dim dt As DataTable = New DataTable()
Dim da As SqlDataAdapter = New SqlDataAdapter(strSQL, myConn)
da.Fill(dt)

Dim excelPackage = New OfficeOpenXml.ExcelPackage
Dim excelWorksheet = excelPackage.Workbook.Worksheets.Add("ProjectStatusReports")
excelWorksheet.Cells("A3").LoadFromDataTable(dt, True)
like image 907
Frank Avatar asked Dec 21 '22 07:12

Frank


1 Answers

This changes the position of the first column to the last in a DataTable:

dt.Columns(0).SetOrdinal(dt.Columns.Count - 1)
  • http://msdn.microsoft.com/en-us/library/system.data.datacolumn.setordinal.aspx
  • http://msdn.microsoft.com/en-us/magazine/cc163495.aspx (search SetOrdinal)

The columns before the addressed ordinal position are all decremented one slot to make room for the change of positioning.

like image 135
Tim Schmelter Avatar answered Jan 21 '23 00:01

Tim Schmelter