Donwload 엑셀 파일에 대한 rails http 응답

Oct 26 2020

나는 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) }

이 코드는 내 프로젝트 파일에 Excel 파일 (output.xlsx)을 저장합니다.

이 "저장 파일 시나리오"를 "브라우저에서 파일 다운로드"로 변환하려면 어떻게해야합니까?

답변

1 Ezenwa Oct 26 2020 at 12:06

config / initializers / mime_types.rb에서 xlsx mime_type을 등록하십시오 (기본적으로 Rails에서는 사용할 수 없습니다).

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

Excel 생성을 수행하는 코드가 작동하고 컨트롤러 메서드 (개인)에 있다고 가정합니다 ( excel_file서비스 / 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

컨트롤러 작업에서 다음과 같이 할 수 있어야합니다.

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 "주어진 바이너리 데이터를 브라우저로 전송합니다". 해당 링크를 통해 더 읽어보기)

보기가 있으면 다운로드 링크를 가질 수 있습니다.

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

사용자는 링크를 통해 엑셀 파일을 다운로드 할 수 있어야합니다.