Rails Rails 中使用 template 文件导出 excel 时,如何指定格式 Excel 97-2004 工作簿 (.xls)

macknight · January 13, 2015 · Last by flowerwrong replied at January 16, 2015 · 4089 hits

def index ...... respond_to do |format| format.html format.csv { send_data @merchants.to_csv } #render text: format.xls do response.headers['Content-Disposition'] = 'attachment; filename="' + @xls_file_name + '.xls"' end end end

然后用的 xls 模板,index.xls.erb

但是生成出来的 excel 文件确实是 xls 后缀,但是另存为的时候,格式是 Excel2004 XML 电子表格 (.xml),而不是 Excel 97-2004 工作簿 (.xls),这个格式在生成 xls 文件时,如何指定?

xls 可是私有格式,你用哪个 gem 做导出

#2 楼 @flowerwrong ,我加了 Mime::Type 这行的。我用的http://railscasts.com/episodes/362-exporting-csv-and-excel?view=asciicastexcel的兼容格式?里的模板方法,帮看看,怎么设置

#4 楼 @macknightmime_types.rb这个文件改成 Mime::Type.register_alias "application/vnd.ms-excel", :xls 看看

#2 楼 @flowerwrong railcast 都要钱,而且还卡,神你是怎么看的

gem 'to_xls'

#7 楼 @liangbin661831 不是都要钱,pro 的要购买,再者 $9/month , 现在 60 块钱就可以全部看完

#9 楼 @flowerwrong 假如我改成生成 xlsx 格式,还使用模板方法的话,怎么弄

#7 楼 @liangbin661831 #9 楼 @flowerwrong 假如我改成生成 xlsx 格式,还使用模板方法的话,怎么弄

#11 楼 @macknight 一样的 先注册

Mime::Type.register "application/xls", :xls
Mime::Type.register "application/xlsx", :xlsx

然后 controller 中 format

format.xls
format.xlsx

最后 name.xls.erb and name.xlsx.erb

You need to Sign in before reply, if you don't have an account, please Sign up first.