Export CSV from Rails for IE

God I hate IE. I spend inordinate amounts of time trying to get the simple crap to work on their browser. The latest was wasting half the morning trying to get IE not to barf on CSV file downloads… here’s the code if anyone’s interested.

This is using FasterCSV but it’s really just the headers you need to be concerned with:

Modified from http://wiki.rubyonrails.org/rails/pages/HowtoExportDataAsCSV

def stream_csv
filename = params[:action] + ".csv"

if request.env['HTTP_USER_AGENT'] =~ /msie/i
headers['Pragma'] = 'public'
headers["Content-type"] = "text/plain"
headers['Cache-Control'] = 'no-cache, must-revalidate, post-check=0, pre-check=0'
headers['Content-Disposition'] = "attachment; filename=\"#{filename}\""
headers['Expires'] = "0"
headers["Content-Type"] ||= 'text/csv'
headers["Content-Disposition"] = "attachment; filename=\"#{filename}\""

render :text => Proc.new { |response, output|
csv = FasterCSV.new(output, :row_sep => "\r\n")
yield csv