shou2017.com
JP

Create Individual Files from CSV Using Ruby

Fri Sep 22, 2017
Sat Aug 10, 2024

I thought this might be useful, so here’s a memo.

Take data entered in Excel, export it as a CSV file, and create individual files for each row. For example, if you input individual scores, you can generate text files for each person to distribute their scores.

Create Individual Files from CSV Using Ruby

First, convert the header part to English.

Create Individual Files from CSV Using Ruby

Then, export it as a CSV file.

Make sure to include # encoding: utf-8. If you forget, you’ll encounter errors.

# encoding: utf-8
require 'csv'

CSV.foreach('sample.csv', headers: true) do |score|
  File.open("#{score['name']}", "w") do |individual|
    individual.puts("Name: #{score['name']}")
    individual.puts("Math: #{score['arithmetic']}")
    individual.puts("English: #{score['english']}")
  end
end

When you run this, it will generate three individual files as shown below.

Create Individual Files from CSV Using Ruby

See Also