The easiest way is to assign two numbers to each record to be written to output.
The first number is a "block" number, in your example there are two "blocks" (from header to footer), so you should assign a "block number" of 1 or 2 to each record.
The second number is a "line number" within each block. This means that the header line always gets line number 1, the footer line always gets line number 2,147,483,647 , and the detail lines get a line number in the range 2 - 2,147,483,646.
Finally sort all your lines first by block number, then by line number.
And output all values to the CSV file except the two numbers.
There are several distinct approaches to this sort of trouble, but I fear you need some more experience before you understand these approaches. Hence I've posted the simplest (yet most time- and CPU- and disk-consuming) approach here. No offense intended.