Zip Excel sheet generated through gem axlsx rails - ruby-on-rails

I'm facing an issue of how to zip the excel sheet generated through gem 'axlsx_rails'. For example:
class SampleController < ApplicationController::Base
def export
if params[:zip]
xxxx
else
render xlsx: 'export', filename: filename, disposition: 'attachment'
end
end
end
In the above example, right now the end user is able to download the excel sheet but if the end user requests a zip file of excel sheet, how can we do that. Because of code in 'else' block the end user is able to download the excel sheet. What I have to do if the user wants the excelsheet to be zipped before download. If you need any further info, plz let me know. Thanks

This is untested code, but try using Zip::ZipOutputStream:
def export
if params[:zip]
compressed_filestream = Zip::ZipOutputStream.write_buffer do |zos|
content = render_to_string xlsx: 'export', filename: filename
zos.put_next_entry(filename)
zos.print content
end
compressed_filestream.rewind
send_data compressed_filestream.read, filename: 'export.zip', type: 'application/zip'
else
render xlsx: 'export', filename: filename, disposition: 'attachment'
end
end
If it doesn't work, create an issue on Github, and after we get it working we can add it to the documentation.

Related

rails http response to Donwload excel file

i saw this code in github
require "csv"
csv_str = CSV.generate do |csv|
csv << ["awesome", "csv"]
end
result = IO.popen("secure-spreadsheet --password secret", "r+") do |io|
io.write(csv_str)
io.close_write
io.read
end
File.open("output.xlsx", "w") { |f| f.write(result) }
this code store a Excel file(output.xlsx) in my project file.
how can i convert this "store file scenario" in to "download the file in the browser"?
In your config/initializers/mime_types.rb register the xlsx mime_type(It is not available in Rails by default) :
Mime::Type.register "application/xlsx", :xlsx
Assuming your code that does the excel generation works and is in a controller method(private) named excel_file (I think its better to extract to a service/lib class):
def excel_file
csv_str = CSV.generate do |csv|
csv << ["awesome", "csv"]
end
IO.popen("secure-spreadsheet --password secret", "r+") do |io|
io.write(csv_str)
io.close_write
io.read
end
end
In your controller action you should be able to do something like this
def download_excel
respond_to do |format|
format.xlsx { send_data excel_file, type: 'application/xlsx; header=present', disposition: "attachment", filename: "output.xlsx" }
end
end
( ActionController#send_data "sends the given binary data to the browser". Read more via that link)
If you have a view, you can have a download link
<%= link_to "Download", your_download_path(format: "xlsx") %>
Users should be able to download the excel file via the link

How to create a file on users machine instead of creating in server and then to download using rails

I am working on to allow download an excel file with the below code:
login = Etc.getlogin
#dataFile = "C:/rails/#{login}data.csv"
csv1=CSV.open(#dataFile, 'w') do |csv|
$data.each do |eachrow|
csv << [eachrow.name+"#gmail.com"]
end
end
send_file(#dataFile, :filename => "#{login}data", :type => "application/csv")
Using the above code, I am able to create a file and write the data.
Instead of this, how do i write the data in csv and get downloaded into users machine instead of saving in local/server.
What you can do is generate a string with the CSV library, using CSV::generate instead of CSV::open.
Controller:
class DataController < ApplicationController
def download
respond_to do |format|
format.csv { send_csv_download }
end
end
private
def send_csv_download
string = CSV.generate do |csv|
#data.each { |row| csv << ["#{row.name}#gmail.com"] }
end
send_data string, filename: 'foo.csv', type: :csv
end
end
config/routes.rb:
get '/download', to: 'data#download'
View:
<%= link_to 'Download CSV', download_path(format: :csv) %>
Note: Obviously, I have no idea where you get your #data from, since it isn't specified in your question.

prawn rails download on open

I use prawn-rails.
I have a show.pdf.prawn view.
I would like to have an action to download this pdf.
I tried the following:
def download
send_data(
show,
filename: "#{custom_name}.pdf",
type: 'application/pdf'
)
end
What it does, is download something called #{custom_name}.pdf but I m unable to open it (falied to load PDF document).
Having it changed to
def download
send_file(
show,
filename: "#{custom_name}.pdf",
type: 'application/pdf'
)
end
I am getting
no implicit conversion of true into String
Please advice.
Should work:
send_data render_to_string("show"), filename: "#{custom_name}.pdf",
type: 'application/pdf'
Also you can use prawnto_2 library:
gem "prawnto_2", require: "prawnto"
and then simply render in the controller action:
def show
respond_to do |format|
format.pdf {
prawnto inline: false,
filename: "#{custom_name}.pdf",
prawn: {} # prawn settings here
}
end
end
But I'm not sure how this library is currently maintained, however still works with Rails 4.2.x.
How about:
def download
response.headers['Content-Disposition'] = 'attachment; filename="' + custom_name + '.pdf"'
render :show, mime_type: Mime::Type["application/pdf"]
end

How to save generated pdf in server in rails

Currently I am generating a pdf using prawn gem of rails. pdf is generated when user hit on this action
def print_pdf
#user = User.find(params[:id])
#details = #user.details_data
respond_to do |format|
format.pdf do
pdf = PrintDetailsPdf.new(#user, view_context, #details)
send_data pdf.render, filename: "#{#user.id}.pdf",
type: 'application/pdf',
disposition: 'inline'
end
end
end
In above action, I generate the pdf and show it in browser and it works perfectly. But I want to show the pdf in browser and also save the pdf at server in public/user_details directory. How can I do that?
There are some good gems that help in file uploading and saving. Here is a list of these gems. Paperclip and Carrierwave are the most popular options.
You could also implement it from scratch. Rails has built-in helpers which make it easy to roll your own solution.
pdf_content = *Content you want to save in the file*
File.open(Rails.root.join('public', 'user_details', filename), 'wb') do |file|
file.write(pdf_content.read)
end
It depends on the complexity of what you want to achieve, but this is totally sufficient for easy file saving tasks. Go here to find more information.
You could do this
pdf_string = render_to_string :template => 'template', :layout => false
File.open("public/userfiles/example.pdf", 'wb') { |
f| f.write(pdf_string) }
end
Render the template to string and then create a file and write that pdf to it..
This should help

How to download file with send_file?

Can someone enlighten me how can I download file with send_file?
I have a file image.jpg inside app/assets/images. I've tried this in my controller:
def download
send_file ("#{Rails.root}/public/images/image.jpg")
end
def download
send_file ("#{Rails.root}/assets/images/image.jpg")
end
def download
send_file ("#{Rails.root}/images/image.jpg")
end
def download
send_file ("/public/images/image.jpg")
end
def download
send_file ("/assets/public/images/image.jpg")
end
def download
send_file ("/assets/images/image.jpg")
end
For each path it says:
ActionController::MissingFile in HomeController#download
Cannot read file 'some_path'
What could be a problem here? Thanks!
Try:
IMAGES_PATH = File.join(Rails.root, "public", "images")
def download
send_file(File.join(IMAGES_PATH, "image.jpg"))
end
In your view =>
<%= link_to "click here to download", signed_feeds_pdf_path(:feed_image_path => feed_image.feedimage.path), target: '_self' %>
In your controller =>
def pdf
file_name = params[:feed_image_path].split('/').last
#filename ="#{Rails.root}/public/uploads/feed_image/feedimage/#{file_name}"
send_file(#filename ,
:type => 'application/pdf/docx/html/htm/doc',
:disposition => 'attachment')
end
soo simple......
well, i suggest you to move your file to public folder. Anyway , do this
send_file(Rails.root.join('app' , 'assets', 'images', 'image.jpg'))
We need to specify the mine type so that it will cache.
send_file ("#{Rails.root}/public"+image.image_path), :type => "image/jpeg", :disposition => 'inline'
For anyone still looking for an answer, send_data and send_file won't work when responding to ajax calls. Instead, try submitting a form or using <a href=..> to call the controller method and download a file.

Resources