Saturday, February 4, 2012

Prompting and letting user save csv in a desired folder

Export excel from Rails application - User gets a link on view and when user clicks on that link a prompt comes asking user to save the exported excel on clients computer at desired location. In this case, you can create excel view and perform view formatting as we do with html page.
Prompting and letting user save csv in a desired folder:
Code snippets:

1. Add in routes:
map.fumasterdatalist 'chart/fumasterexcel', :controller => "chart", :action => "fumaster_excel"

2. Add link on view:
   <%= link_to "Export FU List as Excel", {:controller=> "chart", :action=> "fumaster_excel"}  %>

3. Add action on controller
  def fumaster_excel
      @oprawdatas= Expdatedata.find(:all, :order=> "exp_date asc")
      headers['Content-Type'] = "application/vnd.ms-excel"
      headers['Content-Disposition'] = 'attachment; filename="fuexpreport.xls"'
      headers['Cache-Control'] = ''
      render(:layout=>false)
    end

4. Create a view page which will be exported in excel:

<table "border=1px" cellpadding="2" style="margin: 20px 40px">
  <tr>
   <th>Sl. No.</th>
   <th>ID</th>
   <th>Instrument</th>
    <th>Symbol</th> 
    <th>Created_At&nbsp;&nbsp;&nbsp;</th>
  </tr>

<% i = 0 %>
<% @oprawdatas.each do |import| %>
  <tr>
  <td><%=i = i + 1 %></td>
  <td><%=h import.id %></td>
    <td><%=h import.instrument %></td>
    <td><%=h import.symbol %></td> 
    <td><%=h import.created_at.strftime("%b %d, %Y") %></td>
    <td><%= link_to 'Destroy', {:controller=> "oprawdatas", :action=> "destroy", :id=> import.id}, :confirm => 'Are you sure you want to delete the record?' %></td>
  </tr>
<% end %>
</table>



No comments:

Post a Comment