본문 바로가기

IT/RUBY

Ruby On Rails, CSV 출력

1. CSV

 

CSV에 대한 포스트입니다. CSV가 궁금하시다면 아래의 포스트를 이용해 보아요

 

 

CSV, Comma Separated Values

1. Comma Separated Values(CSV) ・ 위키백과에서 Comma Separated Values 항목을 검색했습니다. CSV는 몇 가지 필드를 쉼표(,)로 구분한 텍스트 데이터 및 텍스트 파일이다. 확장자는. csv이며 MIME 형식은 text..

itbellstone.tistory.com

2. CSV로 저장 방법

 

1) Model 작성

 

・ 예제를 위해 먼저 Model을 만들겠습니다.

 

$ rails generate model speech
Running via Spring preloader in process 5012
      invoke  active_record
      create    db/migrate/20190319064428_create_speeches.rb
      create    app/models/speech.rb
      invoke    test_unit
      create      test/models/speech_test.rb
      create      test/fixtures/speeches.yml

 

・ db/migrate/20190319064428_create_speeches.rb에 아래와 같이 Migrate 파일을 수정합니다.

 

class CreateSpeeches < ActiveRecord::Migration[5.2]
  def change
    create_table :speeches do |t|
      t.string :speech_name
      t.string :speech_saying
      t.timestamps
      t.timestamp :deleted_at
    end
  end
end

 

・ DB에 다음과 같이 데이터를 입력했습니다.

 

id speech_name speech_saying created_at updated_at deleted_at
1 BLOG BELLSTONE 2019-03-14 13:13:47.969492 2019-03-14 13:13:47.969492  
2 BELLSTONE BLOG 2019-03-14 13:13:47.969492 2019-03-14 13:13:47.969492  

 

2) routes.rb 설정

 

・ routes.rb에 아래와 같이 추가했습니다.

 

GET 메서드/speech/download라는 Request 요청이 오면 speech 컨트롤러의 download 메서드를 호출하라는 의미입니다.

 

#speech
  get '/speech/download', to: 'speech#download'
  resources :speech

 

3) View 작성

 

・ app/views/speech의 경로에 index.html.erb 파일을 만들었습니다.

 

・ 그리고, application.html.erb를 약간 수정하였습니다. 작업하실 때는 필요한 부분에 link_to를 추가해주세요!

 

#app/views/layouts/application.html.erb
<!DOCTYPE html>
<html>
  <head>
    <title>Testproject</title>
      <h1>CSV</h1>
      <%= link_to "CSV 다운로드", {controller: :speech, action: "download", format: :csv}%>
      <%= csrf_meta_tags %>
      <%= csp_meta_tag %>
  </head>
  <body>
  </body>
</html>

 

4) Controller 작성

 

・ 다음으로 Controller를 생성했습니다.

 

$ rails generate controller speech
create  app/controllers/speech_controller.rb
      invoke  erb
      create    app/views/speech
      invoke  test_unit
...

 

・ 컨트롤러에 Speech 테이블의 모든 데이터를 speeches.csv라는 파일로 저장하도록 수정하였습니다.

 

class SpeechController < ApplicationController
  #GET /speech/download
  def download
    @speeches = Speech.all
    send_data render_to_string, filename: "speeches.csv"
  end
end

 

5) download.csv.ruby 작성

 

・ download.csv.ruby라는 이름으로 app/views/speech/download.csv.ruby의 경로에 추가했습니다.

 

CSV.generate를 이용하여, DATA를 CSV 파일로 변환합니다.

 

밀리 세컨드로 요구사항이 자주 있기 때문에, 밀리세컨드도 추가하였습니다.

 

require 'csv'

CSV.generate do |csv|
  csv_column_names = %w(NO NAME CONTENT CREATED_AT UPDATED_AT DELETED_AT)
  csv << csv_column_names
  @speeches.each do |speech|
    #시간이 있을 경우 밀리세컨드로 변환
    created_at = speech.created_at.strftime("%F %H:%M:%S.%L") if speech.created_at.present?
    updated_at = speech.updated_at.strftime("%F %H:%M:%S.%L") if speech.updated_at.present?
    deleted_at = speech.deleted_at.strftime("%F %H:%M:%S.%L") if speech.deleted_at.present?

    csv_column_values = [
      speech.id,
      speech.speech_name,
      speech.speech_saying,
      created_at,
      updated_at,
      deleted_at
    ]
        csv << csv_column_values
    end
end

3. 실행

 

・ 서버를 작동시킨 후 localhost:3000/speech를 입력하면 아래와 같은 허접한 화면이 나옵니다.

 

 

 

・ 다운로드를 클릭하면, download에 자동으로 저장됩니다.

 

・ 파일을 열면 아래와 같이 나옵니다. MAC에서 실행해서 그런지 CSV 파일이 아래와 같이 보여요!

 

 

 

・ 그럼 끝!