csv xls export to excel using respond_to spreadsheet - ruby-on-rails

I want to export results generated from my rails app to excel format. distribution_sheet, results and specimens are all models. This is my script in my controller:
def first
#distribution_sheet = DistributionSheet.find(:all, :conditions => ["lifecycle_state = ?","closed"]).last
#results = #distribution_sheet.results
#specimens = #distribution_sheet.specimens
end
include DisplayResultHelper
def show
respond_to do |format|
format.html
format.csv {
#specimens.each do |sp|
send_data(generate_csv([["Lab No","Assay","Batch","Cuttoff"],[sp.id]]),
:filename => "my_data-#{Time.now.to_date.to_s}.csv",
:type => 'text/csv')
end
}
format.xls{
send_data(generate_xls([["Lab No","Assay","Batch","Cuttoff"],[]]),
:filename => 'my_date.xls',
:type => 'application/vnd.ms-excel')
}
end
end
end
This works if I add any words inside the arrays, but once I add sp.id it fails. I want to add the data in sp.id. Any clues?
Mark

I'm not sure which library you're using - but perhaps it requires real strings in those arrays, so try passing in sp.id.to_s instead of just sp.id

Related

Rails: respond_to PDF and HTML that has text as well as Emojis

I'm trying to create & download a html file in pdf format which has paragraph containing text along with Emoticons (Emojis). In output I'm able to get correct text but not the Emojis.
I have dashboard_controller.rb that contains the following function.
def download_dashboard
respond_to do |format|
format.html
format.pdf do
html = render_to_string(:layout => false, :action => "download_dashboard.html.haml")
send_data(html, :filename => "dashboard.html", :type => 'application/pdf')
end
end
end
Here, download_dashboard.html.haml has the following code
%p= Hello, World!😃
But the download file dashboard.htmloutput I'm getting is something different like this:
The correct output should be like this:
How can I achieve the correct output?
include char='utf-8' in download_dashboard.html.haml:
%meta{:charset => "utf-8"}

Rails Exporting CSV ignore blanks

I'm trying to create a simple CSV export in Rails. The export works fine except when deleting/archiving table items. I'm guessing this is because the export is encountering blanks.
This is working:
= link_to transactions_path(format: :csv) do
Except when there is a item missing from the transaction.
Tried this
= link_to transactions_path(format: :csv,skip_blanks: true) do
but I still get a ERR_INVALID_RESPONSE when calling the export
TransactionController:
respond_to :html, :json, :csv
def index
#shops = current_user.shops
respond_with(#shops) do |format|
format.csv do
response.headers['Content-Type'] = 'text/csv'
response.headers['Content-Disposition'] = "attachment; filename=transactions-#{Time.now.strftime('%Y%m%d%H%M')}.csv"
render inline: #shops.to_csv
end
end
end
Any suggestions?
Change to_csv to pass skip_blanks.
#shops.to_csv(skip_blanks: true)
If you want a link to download a CSV file, you should use send_data instead. If you want to display the file in the browser, use render text: #shops.to_csv
http://railscasts.com/episodes/362-exporting-csv-and-excel
respond_to :html, :json, :csv
def index
#shops = current_user.shops
respond_with(#shops) do |format|
format.csv do
send_data #shops.to_csv, type:'text/csv', filename: "transactions-#{Time.now.strftime('%Y%m%d%H%M')}.csv"
end
end
end
Change your link_to back to what you had before.
= link_to transactions_path(format: :csv)
Maybe using send_data:
def index
respond_to do |format|
format.csv { send_data #current_user.shops.to_csv, filename: "transactions-#{Time.now.strftime('%Y%m%d%H%M')}.csv" }
end
end
Also, is the to_csv an instance method?

Rails render array to pdf with prawn

I need to render my #manufacturers array to pdf, but do it only via click on some link in view...
Now i have such code
def index
#manufacturers = Manufacturer.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: #manufacturers }
format.pdf { render :layout => false }
end
end
I see a lot of examples in web, but i didn't found clear and actual example... Just how simple do in a4 pdf table with my array #manufacturers ?
In addition to prawn, use the prawnto rails plugin to help with rendering the PDF as a template.
See https://github.com/prior/prawnto for the plugin and http://railscasts.com/episodes/153-pdfs-with-prawn for how to use it.
[Note: the Report gem currently only generates on letter-size paper, patch for A4 would be welcome!]
You can use the Report gem, which generates PDF using Prawn but also XLSX and CSV.
# a fake Manufacturer class - you probably have an ActiveRecord model
Manufacturer = Struct.new(:name, :gsa)
require 'report'
class ManufacturerReport < Report
table 'Manufacturers' do
head do
row 'Manufacturer report'
end
body do
rows :manufacturers
column 'Name', :name
column 'GSA?', :gsa
end
end
# you would want this so that you can pass in an array
# attr_reader :manufacturers
# def initialize(manufacturers)
# #manufacturers = manufacturers
# end
def manufacturers
[
Manufacturer.new('Ford', true),
Manufacturer.new('Fischer', false),
Manufacturer.new('Tesla', nil),
]
end
end
When you call report.pdf.path, a PDF is generating in the tmp directory:
report = ManufacturerReport.new
puts report.pdf.path #=> /tmp/185051406_Report__Pdf.pdf
puts report.xlsx.path #=> /tmp/185050541_Report__Xlsx.xlsx
You can do it in your controller like:
#manufacturers = Manufacturer.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: #manufacturers }
format.pdf do
report = ManufacturerReport.new(#manufacturers) # using the commented-out code
send_file report.pdf.path, :type => 'application/pdf', :disposition => 'attachment', :filename => 'ManufacturersReport.pdf'
# tmp files are periodically cleaned up by the operating system, but if you want to be extra clean you can call
# report.cleanup
# but this may remove the tmp files before apache/nginx/etc. finishes delivering the file
end
end
End result:
PDF
XLSX
Note that the XLSX has an autofilter added for you automatically.

CSV renders in Safari view but I want it to download a file

I have configured a custom mime type:
ActionController::Renderers.add :csv do |csv, options|
self.content_type ||= Mime::CSV
self.response_body = csv.respond_to?(:to_csv) ? csv.to_csv : csv
end
and a respond_to block in my controller:
respond_to do |format|
format.html
format.csv { render :csv => csv_code}
end
Using Firefox and Chrome, the .csv renders to a file which is downloaded. Using Safari the .csv is rendered as a view: How can I change this and force it to download as a file?
See a screen shot of the problem:
Try
respond_to do |format|
format.html
format.csv do
response.headers['Content-Type'] = 'text/csv'
response.headers['Content-Disposition'] = 'attachment; filename=thefile.csv'
render :csv => csv_code
end
end
if this doesn't work, try using
send_file "path/to/file.csv", :disposition => "attachment"
The way I have this working in an old Rails 2 app is using send_data instead of render in the controller. E.g.:
def csv
... # build data
send_data csv_data_as_string, :filename => "#{filename}.csv", :type => 'text/csv'
end

rails how to export data to excel

i have table like the following
now, i want to export this to excel, so i can open it in ms excel
You can use FasterCSV gem.
You can either use to_csv method.
def index
#records = ....
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => #records }
format.csv { #records.to_csv }
end
end
or customize the output and use send_data method in the controller.
format.csv do
csv_string = FasterCSV.generate do |csv|
# header row
csv << ["id", "Column1", "Column1"]
# data rows
#records.each do |r|
csv << [r.id, r.column1, r.column2]
end
# send it to the browser
send_data csv_string,
:type => 'text/csv; charset=iso-8859-1; header=present',
:disposition => "attachment; filename=records.csv"
end
I would advice to use Spreadsheet which is mature. I'm using it with Rails 3 with no problems.
The overall process would be:
book = Spreadsheet::Workbook.new
sheet = book.create_worksheet :name => 'Customers'
sheet.row(0).concat %w{Name Country Acknowlegement}
book.write '/path/to/output/excel-file.xls'
Ruby 1.9 has a built in CSV library with very similar API as the FasterCSV gem (actually the gem got integrated into Ruby!).

Resources