Sort a table in ClosedXML while keeping header row

给你一囗甜甜゛ 提交于 2019-12-11 06:09:56

问题


I've tried a few methods of sorting in ClosedXML but they've all had the same results: the first row of data becomes the new header in excel.

Here's the code I've used so far:

Dim dtChangedScores As New DataTable
dtChangedScores.Columns.Add("Name")
dtChangedScores.Columns.Add("Old Score")
dtChangedScores.Columns.Add("New Score")

Dim dr As DataRow = dtChangedScores.NewRow
dr("Name") = "aaa"
dr("Old Score") = "bbb"
dr("New Score") = "bbb"
dtChangedScores.Rows.Add(dr)
'etc....

Dim wb = New XLWorkbook
Dim ws = wb.Worksheets.Add(dtChangedScores, "Scores")
Dim rangeTable = ws.Table(0).RangeUsed()
rangeTable.Sort()

dtChanged scores is a datatable

How can I keep the original header row while sorting the data?


回答1:


If you can sort your data before you take it to Excel then the following code should do it. I displayed the data so you can see how it worked.

Private Sub OPCode()
    'Create a DataTable
    Dim dtChangedScores As New DataTable
    dtChangedScores.Columns.Add("Name")
    dtChangedScores.Columns.Add("Old Score")
    dtChangedScores.Columns.Add("New Score")
    'Add some data
    dtChangedScores.Rows.Add("Joe", 22, 30)
    dtChangedScores.Rows.Add("Pete", 19, 20)
    dtChangedScores.Rows.Add("Bob", 17, 20)
    'You can use the .Sort method of the DataView
    dtChangedScores.DefaultView.Sort = "Name"
    DataGridView1.DataSource = dtChangedScores
End Sub

If you need to do this in Excel. Work in Excel for a bit to see how it is done. You will see that you select all the data except the header row. Maybe record a macro then translate then translate it to vb.net.



来源:https://stackoverflow.com/questions/58595614/sort-a-table-in-closedxml-while-keeping-header-row

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!