You didn't really tell us what is going wrong. If it isn't downloading your file then either you're getting an error (which you need to share with us) or there is something wrong elsewhere. Step through your code line by line until either the error occurs or you get to the end.
Also take a look on the browser side. Presumably you're clicking a link or something to trigger the browser to download the file. Use the Developer Tools (F12) in the browser and look at the network tab. What response is sent back from the browser for this request? Specifically you're interested in the status code, content length, headers, etc. I wonder if it is a browser issue and not related to your code at all.