我正在尝试将大量数据从数据库导出到 csv 文件,但这需要很长时间,并且担心我会遇到严重的内存问题。
有谁知道在不增加内存的情况下导出 CSV 的更好方法?如果是这样,你能告诉我怎么做吗?谢谢。
这是我的控制器:
def users_export
File.new("users_export.csv", "w") # creates new file to write to
@todays_date = Time.now.strftime("%m-%d-%Y")
@outfile = @todays_date + ".csv"
@users = User.select('id, login, email, last_login, created_at, updated_at')
FasterCSV.open("users_export.csv", "w+") do |csv|
csv << [ @todays_date ]
csv << [ "id","login","email","last_login", "created_at", "updated_at" ]
@users.find_each do |u|
csv << [ u.id, u.login, u.email, u.last_login, u.created_at, u.updated_at ]
end
end
send_file "users_export.csv",
:type => 'text/csv; charset=iso-8859-1; header=present',
:disposition => "attachment; filename=#{@outfile}"
end