4
votes

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)
1
You only want to swap first and last column's positions are all? - Tim Schmelter
well.... I basically wanted to rearrange the column positions - Frank

1 Answers

11
votes

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

dt.Columns(0).SetOrdinal(dt.Columns.Count - 1)

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