简体   繁体   中英

Print CSV headers in bold text in Rails

My CSV is getting generated totally correct. I want to print the CSV headers bold. Is there any way to print them in bold.

My code that prints the simple 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
%>

Thanks in advance!!

this can't be done; CSV is a text plain format.

So you will need another file type document to do this.

I used a gem called ' axlsx_rails ' to help out and its really simple

example of my controller

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

example of my xlsx view

#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 that view

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

if you want to see the sample code in action I created a git repo where you can see all I did https://github.com/mzaragoza/sample_exporting_xls

Hope that this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM