0

I'm creating one CSV file using csv_table_view(Code copied below). I want to prefix CSV data with some text message. This message should be in red color and bold. Is there any way by which I can specify text color and bold property in the message string. Here is my code-

def render_csv(view)
    ctv = CsvTableView.new(view)
    csv = ctv.render
    render_csv_content(csv, ctv)
end

def render_csv_content(csv, ctv)
    headers['Content-Type'] = "application/vnd.ms-excel"
    headers['Content-Length'] = csv.size
    headers['Cache-Control'] = ''
    headers['Content-Disposition'] = %{attachment; filename="#{ctv.filename}"; size=#{csv.size}}
    render :text => csv
  end

def render
    @table.prepare(true)
    @ret = []
    @ret ="Hello this message should be red and bold \n"
    @ret +=  @table.columns.map do |col|
      col.split ? col.split.map { |c| "#{col.name} #{c}" }.join(",") : csv_escape(col.name)
    end.join(",") + "\n" +
            @table.all_rows.map { |row| row.map { |col| csv_escape(col) 
            }.join(",") }.join("\n") 
end

I read in one article that with content type application/vnd.ms-excel, we can not add formatting to the text. Any idea on that? Thanks in advance.

3
  • 2
    There is no way to add formatting to a CSV file, by definition it's a text only file. You could, instead, generate an excel file. Commented May 31, 2019 at 10:34
  • @Yule Thanks for the reply, okay then I'll try with creating excel file. Commented May 31, 2019 at 10:36
  • 1
    It seems like you are trying to generate three different things here. The response header is saying it's Excel, the content you want to output is CSV, but also HTML because CSV is just a plain file of comma-separate values. You could try generating HTML with some text on top and a table of values, if it's possible Excel supports importing HTML like that (not sure). Commented May 31, 2019 at 10:38

1 Answer 1

2

There is no way to add formatting to CSV file. It can only ever be text.

It looks as though you're wanting an excel file. One suggestion is to use the spreadsheet gem. This allows for formatting and output as an XLS file. The guide is useful to see how to do this.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.