rails http phản hồi cho Donwload tệp excel

Oct 26 2020

tôi đã thấy mã này trên 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) }

mã này lưu trữ một tệp Excel (output.xlsx) trong tệp dự án của tôi.

Làm cách nào để chuyển đổi "kịch bản tệp lưu trữ" này thành "tải tệp xuống trong trình duyệt"?

Trả lời

1 Ezenwa Oct 26 2020 at 12:06

Trong config / initializers / mime_types.rb của bạn đăng ký xlsx mime_type (Nó không có sẵn trong Rails theo mặc định):

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

Giả sử mã của bạn có hoạt động tạo excel và nằm trong một phương thức controller (private) được đặt tên excel_file(tôi nghĩ tốt hơn nên trích xuất vào một lớp dịch vụ / lib):

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

Trong hành động điều khiển của bạn, bạn sẽ có thể làm điều gì đó như thế này

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 "gửi dữ liệu nhị phân đã cho tới trình duyệt". Đọc thêm qua liên kết đó)

Các bạn xem có thể cho link download

<%= link_to "Download", your_download_path(format: "xlsx") %>

Người dùng có thể tải xuống tệp excel thông qua liên kết