Closed zmd94 closed 6 years ago
You need to tell the controller, that it should send the file, eg.:
# after closing the xlsx
send_file "#{current_user.callsign}.xlsx",
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
However it's better to write the file to a Tempfile
(if it is large) or a StringIO
if it is small.
If you always write to the same file, you risk file corruption if the action is called in parallel by users with the same callsign. You would also have to remove the file manually, while the Tempfile
is automatically deleted after the action finishes.
Example with Tempfile
:
Tempfile.open do |io|
xlsx = Xlsxtream::Workbook.new(io)
# write worksheet …
xlsx.close
send_file io.path,
filename: "#{current_user.callsign}.xlsx",
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
end
Example with StringIO
:
io = StringIO.new
xlsx = Xlsxtream::Workbook.new(io)
# write worksheet …
xlsx.close
send_data io.string,
filename: "#{current_user.callsign}.xlsx",
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
Many thanks Felix. I have tried the code with Tempfile
, yet it is not working. So, I modify the code little bit and everything is working well now. Below if full working code:
def export
@logging ||= Logging.new
@qsos = current_user.logging.qsos
tmp_file = Tempfile.new(["#{current_user.callsign}", ".xlsx"])
Xlsxtream::Workbook.open(tmp_file.path, font: { name: 'Arial', size: 11 }) do |xlsx|
xlsx.write_worksheet 'Sheet1' do |sheet|
sheet << ['DATE', 'TIME', 'CQ STATION', 'CALLSIGN', 'BAND', 'FREQ', 'MODE', 'RECV', 'SENT']
@qsos.each do |qso|
sheet << [qso.time.strftime("%Y-%m-%d"), qso.time.strftime("%H%M"), qso.logging.user.callsign.upcase, qso.callsign, qso.band, "#{(qso.frequency.to_f).round(3)} MHz", qso.mode, qso.rst_rcvd, qso.rst_sent]
end
end
end
send_file tmp_file,
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
end
Next, I suggest you to update the README.md file or I can help you. I will pull request for it.
Regards,
9W2ZOW - Malaysia.
Hi, I want to ask how to configure xlsxtream properly so that user can download the .xlsx file.
Firstly, what I have done is create code as below to link to export path:
Above code is located in my index.html.erb file.
Then, below is the code in my dashboard_controller.erb file for the export function:
Yet, when I click the "Export All" button, it return below errors:
However, although there is errors, the .xlsx file still being successfully created. Yet it is in local directory. Why?
What I do wrong? Thank you.