Share via

Invoking a sort using OpenXML

Jim Wilson 21 Reputation points
2021-07-28T17:30:43.95+00:00

I have been producing excel files with open XML and I know how to set up the sort criteria. What I don't understand is how to invoke the actual sort. Any help will be appreciated.

Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.


Answer accepted by question author

Timon Yang-MSFT 9,611 Reputation points
2021-07-29T05:53:09.373+00:00

Could you please show some of your current code and let us move on based on your code?

I used ClosedXml to write some code, this library is a layer of encapsulation of OpenXML API, see if this is suitable for you.

        static void Main(string[] args)  
        {  
            DataTable dataTable = GetDataTable();  
            ExportData();  
        }  
        static DataTable GetDataTable()  
        {  
            DataTable dataTable = new DataTable();  
            dataTable.Columns.Add("ID", typeof(int));  
            dataTable.Columns.Add("Name", typeof(string));  
            dataTable.Columns.Add("Math", typeof(double));  
            dataTable.Columns.Add("Science", typeof(double));  
            dataTable.Columns.Add("History", typeof(double));  
  
            dataTable.Rows.Add(1, "Timon", 75.2, 98, 74);  
            dataTable.Rows.Add(2, "Tom", 85, 83, 54);  
            dataTable.Rows.Add(3, "Jerry", 35.4, 77, 25);  
            return dataTable;  
        }  
        private static void ExportData()  
        {  
            var wb = new XLWorkbook();  
            DataTable dt = GetDataTable();  
  
            var wsTable = wb.Worksheets.Add(dt,"Table");  
            var rangeTable = wsTable.RangeUsed();  
            var table = rangeTable.CopyTo(wsTable.Column(wsTable.LastColumnUsed().ColumnNumber() + 3)).CreateTable();  
            table.Sort("History Asc");  
  
            wb.SaveAs(@"C:\xxx\SortExamples1.xlsx");  
        }  

If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

Was this answer helpful?

0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Jim Wilson 21 Reputation points
    2021-07-29T11:45:50.93+00:00

    @openspecs-office-fileformats

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.