0

I'm using FasterCsv to export data to CSV files in rails.Now I want to format the values in CSV file

  title = ["NAME", "ID", "INSTITUTION"]
  output.write FasterCSV.generate_line(title)

like coloring, Bold etc.

how to do that?any help..

1
  • If this is Ruby 1.9, note that FasterCSV is now the implementation for the built-in CSV library. Commented Jan 31, 2011 at 14:21

3 Answers 3

2

There is nothing to style in a CSV file, it is just raw data, and csv is meant for plain text format file..

refer this sitepoint link for reference.. http://www.sitepoint.com/forums/showthread.php?t=532277

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

Comments

2

As others have mentioned, you can't add formatting to CSV files.

CSV means, literally, "Comma Separated Values". This is, a plain text file with values, separated with commas. Formatting isn't included.

If you want to include formatting (for Excel, I pressume) you will have to generate a different kind of file - for example an xls file.

You can do so by using the Spreadsheet gem.

I haven't personally used that gem for formatting. After a quick google search I found this forum on which they show how to use it for changing the format of a cell (background color on this case). Warning: I haven't tried this code myself and I'm not 100% certain it is current.

require 'rubygems'
require 'spreadsheet'

Spreadsheet.client_encoding = 'UTF-8'

book = Spreadsheet::Workbook.new

class ColorFormat < Spreadsheet::Format
  def initialize(color)
    super :pattern => 1, :pattern_fg_color => color
  end
end

sheet = book.create_worksheet :name => 'My fruits'

fruits = {
  'apple' => :red,
  'lemon' => :yellow,
  'orange' => :orange
}.each_with_index do |(fruit, color), i|
  sheet[0, i] = fruit
  sheet.row(0).set_format(i, ColorFormat.new(color))
end

sheet.row(0).height = 14 

book.write '/home/serge/Documents/fruits.xls'

Comments

0

CSV is a plain text file format, AFAIK you cant supply font attributes in it.

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.