【问题标题】:Cannot send more than one table to an xlsx sheet using axlsx无法使用 axlsx 将多个表发送到 xlsx 工作表
【发布时间】:2016-05-26 06:48:54
【问题描述】:

我正在使用 axlsx_rails 在应用程序中生成报告,并且我正在尝试使用此 gem 编写我的第一个(曾经)报告。该报告是为了允许用户为报告选择一匹特定的马并将马及其对应的小马驹输出到同一张纸上。只有一个表(马表)用于此目的。通过马 ID 查询同一个表到 Dam_id(如果是母马)或 Sire 字段(如果马是种马),可以找到马的小马驹。为简单起见,由于查询工作正常,我没有包含确定是母马还是种马的代码。

我成功地将马输出到电子表格,但是虽然马驹是在控制器中生成的(我使用调试器检查过),但它们在工作表输出中没有被识别。

相关代码包括:

  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 匹小马驹。

  1. 在 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 电子表格显示:

第一行:列标题, 第二行:所选马匹的信息, 第三行:空 第四行:FOALINGS 第五行:小马驹的标题 第六行:“NO FOALS”

非常感谢任何可以帮助我发现为什么没有打印小马驹信息的帮助。

提前谢谢你,

【问题讨论】:

  • 只是一个问题,你的变量真的是@foalings 而不是@foalings?
  • 另外,您可能会检查您的小马行中的 nil 值。 Axlsx 可能不接受单元格的 nil 值。

标签: ruby-on-rails axlsx


【解决方案1】:

谢谢你,诺埃尔。

这简直太愚蠢了。是马驹不是污秽。经验教训:在做新事物时,不要因为做新事物而假设错误是由于复杂原因造成的——首先检查愚蠢的简单错误!

【讨论】:

    猜你喜欢
    • 2014-06-21
    • 2020-01-03
    • 1970-01-01
    • 1970-01-01
    • 2019-04-16
    • 2020-08-19
    • 1970-01-01
    • 2014-03-22
    • 1970-01-01
    相关资源
    最近更新 更多