[英]Download XLSX file created by XlsxWriter in rails
我正在嘗試將xlsx文件保存到瀏覽器下載中,單擊瀏覽器按鈕時會激活以下功能
def trip_bit
@car = Car.find(params[:id])
@t = @car.trips.all
@trips = @t.order(:started_at)
if @trips then
doc = XlsxWriter.new
doc.quiet_booleans!
sheet = doc.add_sheet("Vitácora de Viajes "+@car.model+' '+@car.year.to_s)
sheet.freeze_top_left = 'A2'
sheet.add_row(['Salida', 'Llegada', 'Origen', 'Destino', 'Distancia', 'Duración', 'Score'])
@trips.each do |trip|
sheet.add_row([trip.started_at.to_s, trip.finished_at.to_s, if trip.origin then trip.origin.address end, if trip.destination then trip.destination.address end, trip.distance.to_s+'km', trip.duration.to_s+'min', trip.grade])
end
sheet.add_row(["","","","Total", @trips.map { |trip| trip.distance }.sum.to_s+"km", @trips.map { |trip| trip.duration}.sum.to_s+"min", ""])
else
redirect_to my_car_details_path
flash.now[:alert] = 'Este coche no tiene viajes registrados'
end
send_file doc, :filename => "bitacora.xlsx"
end
創建了xlsx文件doc
並將其保存到本地文件系統,但是我找不到將其發送到瀏覽器下載的方法。
在查看了send_file
和XlsxWriter的文檔之后,該錯誤告訴您它正在期待一個String,但是您正在向其傳遞XlsxWriter類型的對象。 您可以嘗試使用path
方法來告訴sendfile
文件所在的位置...
send_file(doc.path, :disposition => 'attachment', :filename => "bitacora.xlsx", type: "application/xml")
您沒有指示Rails應用程序的任何結構,因此我假設這是一種控制器方法。 您可能可以按照以下方式進行操作:
def trip_bit
@car = Car.find(params[:id])
@t = @car.trips.all
@trips = @t.order(:started_at)
if @trips then
doc = XlsxWriter.new
doc.quiet_booleans!
sheet = doc.add_sheet("Vitácora de Viajes "+@car.model+' '+@car.year.to_s)
sheet.freeze_top_left = 'A2'
sheet.add_row(['Salida', 'Llegada', 'Origen', 'Destino', 'Distancia', 'Duración', 'Score'])
@trips.each do |trip|
sheet.add_row([trip.started_at.to_s, trip.finished_at.to_s, if trip.origin then trip.origin.address end, if trip.destination then trip.destination.address end, trip.distance.to_s+'km', trip.duration.to_s+'min', trip.grade])
end
sheet.add_row(["","","","Total", @trips.map { |trip| trip.distance }.sum.to_s+"km", @trips.map { |trip| trip.duration}.sum.to_s+"min", ""])
else
redirect_to my_car_details_path
flash.now[:alert] = 'Este coche no tiene viajes registrados'
end
respond_to do |format|
format.xlsx
end
end
上面的代碼是直截了當的猜測,因為XlsxWriter是C庫的綁定,並且從Rails的角度來看文檔非常薄,對我幾乎沒有用。 我一直在使用axlsx_rails gem。 它使您可以定義一個模板,並只需將該模板傳遞給Rails數據結構即可。 我強烈建議您在以下位置進行檢查: https : //github.com/straydogstudio/axlsx_rails
它使您可以保持Rails式的工作方式。 當我要將用戶電子表格導出到xlsx時,只需在控制器中執行以下操作:
def index
@users = User.active
respond_to do |format|
format.html
format.xlsx
end
end
然后在我的index.html.erb
旁邊的視圖中,有一個名為index.xlsx.axlsx
的文件,看起來像:
wb = xlsx_package.workbook
wb.add_worksheet(name: "Users") do |sheet|
sheet.add_row ['User', 'User Access Role']
@users.each do |user|
sheet.add_row [user.email, user.role.name]
end
end
如您所見,模板中具有創建電子表格的邏輯。 您執行此操作的方式非常容易出錯且雜亂無章。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.