[Ruby on Rails] CSV Import/Export

Tadashi Shigeoka ·  Thu, January 24, 2013

Here’s reference information for implementing CSV import/export functionality in Ruby on Rails.

Ruby 1.9 adopts FasterCSV as the standard CSV class, so you can use it immediately with require “csv”.

FasterCSV Documentation

Class: CSV (Ruby 1.9.3)

CSV Import/Export Implementation Samples

RailsCast

Ruby on Rails Screencasts - RailsCasts

CSV Import

#396 Importing CSV and Excel - RailsCasts

Uses the roo gem which manipulates spreadsheets (Open Office, Excel, Google Spreadsheets, etc.).

Empact/roo · GitHub

roo: Ruby Library for Manipulating Spreadsheets « TORQUES LABS

CSV Export

#362 Exporting CSV and Excel - RailsCasts

CSV Output with Ruby1.9 and Rails (SJIS) #Rails #Ruby - Qiita

[rails] Creating and Outputting CSV Memo | Oreseka


CSV Character Encoding Conversion

CSV files are often created from Excel, so you need to convert the character encoding from Shift_JIS to UTF-8.

This knowledge is summarized here:

Loading CSV with Character Encoding Conversion #Ruby - Qiita

Uploading CSV Files in rails c

Normally, you use the fixture_file_upload method in tests to upload CSV files, then call the import class method added to the model.

> include ActionDispatch::TestProcess
> file = fixture_file_upload "tmp/test.csv", "text/comma-separated-values"
 => #> 
> Product.import(file)
   (0.2ms)  BEGIN
["a", "b", "c", "d"]
["1", "2", "3", "4"]
   (0.1ms)  COMMIT
 => <#CSV io_type:File io_path:"/var/folders/46/bg9j7wkn5qg9n895016mlvk00000gn/T/test.csv20130124-12060-h3mn08" encoding:UTF-8 lineno:2 col_sep:"," row_sep:"\\r" quote_char:"\\""> 

Reference Information

That’s all from the Gemba.