在Rails中以粗体文本打印CSV标题

时间:2016-08-19 10:11:13

标签: ruby-on-rails csv ruby-on-rails-4 export-to-csv

我的CSV生成完全正确。我想打印CSV标题粗体。有没有办法以粗体打印它们。

我打印简单CSV的代码。

<%= CSV.generate do |csv|

    csv << ["REF", "Customer Name", "Property Address", "Moving Date", "Mobile Phone", "Operator", "Status"]
    @results.each do |result|
        csv << [result.id, result.customer_name, result.address_label, result.moving_date.strftime("%b %d, %Y"), "", result.operator.try(:name), result.status ]

end.html_safe
%>

提前致谢!!

2 个答案:

答案 0 :(得分:2)

这无法完成; CSV是纯文本格式。

因此,您需要另一个文件类型文档才能执行此操作。

答案 1 :(得分:1)

我使用了名为&#39; axlsx_rails&#39;帮忙,真的很简单

我的控制器示例

class ProductsController < ApplicationController
  def index
    @products = Product.order('created_at DESC')
    respond_to do |format|
      format.html
      format.xlsx {
        response.headers['Content-Disposition'] = 'attachment; filename="all_products.xlsx"'
      }
    end
  end
end

我的xlsx视图示例

#app/views/products/index.xlsx.axlsx
wb = xlsx_package.workbook
wb.styles do |style|
  header_cell = style.add_style(b: true)

  wb.add_worksheet(name: "Products") do |sheet|
    sheet.add_row ["Title", "Price"], :style=>[header_cell, header_cell]
    @products.each do |product|
     sheet.add_row [product.title, product.price]
    end
  end
end

链接到该视图

<%= link_to 'Download as .xlsx', products_path(format: :xlsx) %>

如果您想查看示例代码,我创建了一个git repo,您​​可以看到我所做的一切https://github.com/mzaragoza/sample_exporting_xls

希望这有帮助