2016-05-26 27 views
0

我正在使用axlsx_rails在應用程序中生成報表,並且正在嘗試使用此gem編寫我的第一個(以前的)報表。該報告允許用戶爲報告選擇特定的馬並輸出該馬,並將其對應的馬駒輸出到同一張紙上。只有一張桌子(馬桌)用於此目的。一匹馬的馬駒可以通過查詢同一張馬匹ID來發現Dam_id(如果是母馬)或Sire場(如果馬是一匹馬),則可以找到馬駒。爲了簡單起見,由於查詢工作正常,我沒有包括確定是母馬還是種馬的代碼。無法使用axlsx將多個表發送到xlsx表

我成功地將馬輸出到電子表格,但雖然馬駒是在控制器中生成的(我用調試器來檢查),但它們在表格輸出中未被識別。

相關的代碼包括以下各項:

  1. 在index_by_horse_report.html.erb,馬首先選擇,然後:

    .... 
    
        <%= link_to 'Download as horse_report.xlsx', index_by_horse_report_path(format: :xlsx) %> 
    
        .... 
    
  2. 在控制器:

    def index_by_horse_report 
        @horses = Horse.find_by_sql ["SELECT horses.id.....WHERE horses.id = ? ", @horse_id] 
        @horses.each do |horse| 
         @foalings = Horse.find_by_sql ["SELECT horses.id...... WHERE horses.sire_id = ?", horse.id] 
        end 
        respond_to do |format| 
         format.html 
         format.xlsx { 
         response.headers['Content-Disposition'] = 'attachment; filename="horse_report.xlsx"' 
        } 
        end 
    end 
    

查詢返回1匹馬和2匹馬駒。

  • 在index_by_horse_report.xlsx.axlsx:

    wb = xlsx_package.workbook 
    
        wb.add_worksheet(name: "Horse Report") do |sheet| 
        sheet.add_row ["NAME","REGISTRATION#1","REGISTRATION#2", "SIRE", "DAM", "FOALING DATE", "BREED", "Colour", "GENDER", "OWNER", "DATE ARRIVED", "DATE LEFT", "NOTES" ] 
        @horses.each do |horse| 
         sheet.add_row [horse.horse_name,horse.registration_number,horse.registration_number_2, horse.sire_name, horse.dam_name, horse.foaling_date, horse.breed_name, horse.colour_name, horse.gender_name, horse.owner, horse.arrival_date, horse.date_left, horse.notes ] 
         sheet.add_row [""] 
         sheet.add_row ["FOALINGS"] 
         sheet.add_row ["NAME","REGISTRATION#1","REGISTRATION#2", "SIRE", "SIRE/DAM", "FOALING DATE", "BREED", "Colour", "GENDER", "OWNER", "NOTES" ] 
         if @foulings 
         @foulings.each do |foul| 
          sheet.add_row[foul.horse_name, foul.registration_number....] 
         end 
         else 
          sheet.add_row ["NO FOALS"]  
         end 
        end 
        end 
        end 
    
  • Excel電子表格示出了:

    第一行:列標題, 二排:參考匹配的馬, 第三排:空 第四排:發球 第五排:小馬標題 Sixt h行:「NO FOALS」

    任何可以幫助我發現爲什麼不打印馬駒信息的幫助將非常感激。

    感謝您提前,

    +0

    只是一個問題,你的變量真的是@foalings而不是@foulings? – noel

    +1

    另外,你可能會檢查你的馬駒行中的零值。 Axlsx可能不接受單元格的零值。 – noel

    回答

    0

    謝謝諾埃爾。

    這簡直是愚蠢的。這是煽情而不是褻瀆。獲得的經驗:在做新事情時,不要因爲做一些新事情而錯誤歸因於複雜的原因 - 首先檢查愚蠢的簡單錯誤!

    相關問題