Skip to content

Instantly share code, notes, and snippets.

@komasaru
Last active April 19, 2018 05:26
Show Gist options
  • Save komasaru/6338290 to your computer and use it in GitHub Desktop.
Save komasaru/6338290 to your computer and use it in GitHub Desktop.
Ruby script to convert a csv file to html table tags.
#= CSV -> table 変換
# :CSV ファイルを table タグに変換する
# 第1引数:変換対象の CSV ファイル名
# 第2引数:align を c,l,l,r,r,l のように指定(省略可、デフォルトは "l")
#---------------------------------------------------------------------------------
#++
require 'csv'
# [CLASS] 引数
class Arg
def initialize
@aligns = Array.new
end
# 引数取得
def get_args
begin
# CSV ファイル名取得
@csv_file = ARGV[0]
# CSV ファイル存在チェック
unless File.exist?(@csv_file)
puts "[ERROR] Can't found #{@csv_file}"
exit
end
# align 情報取得
return unless ARGV[1]
ARGV[1].split(",").collect do |a|
if ["l", "L"].include?(a[0])
@aligns << "l"
elsif ["c", "C"].include?(a[0])
@aligns << "c"
elsif ["r", "R"].include?(a[0])
@aligns << "r"
else
@aligns << "l"
end
end
rescue => e
STDERR.puts "[ERROR][#{self.class.name}.get_args] #{e}"
exit 1
end
end
# CSV ファイル名返却
def get_csv_file
return @csv_file
end
# align 情報返却
def get_aligns
return @aligns
end
end
# [CLASS] CSV -> table 変換
class Csv2Table
def initialize(csv_file, aligns)
@csv_file = csv_file
@aligns = aligns
@html_file = File.dirname(csv_file) + "/" +
File.basename(csv_file, File.extname(csv_file)) + ".html"
end
# CSV -> table 変換
def convert
begin
# CSV ファイル読み込み
csv = CSV.open(@csv_file, "r")
# HTML ファイル書き込み
html = File.open(@html_file, "w")
html.puts "<table>"
csv.each do |row|
html.puts " <tr>"
row.each_with_index do |col, i|
align = @aligns[i]
html.print " <td"
case align
when "l"
html.print " align=\"left\">"
when "c"
html.print " align=\"center\">"
when "r"
html.print " align=\"right\">"
else
html.print ">"
end
html.puts "#{col}</td>"
end
html.puts " </tr>"
end
html.puts "</table>"
rescue => e
STDERR.puts "[ERROR][#{self.class.name}.convert] #{e}"
exit 1
end
end
end
begin
# 引数取得
obj_args = Arg.new
obj_args.get_args
csv_file = obj_args.get_csv_file
aligns = obj_args.get_aligns
# CSV -> table 変換
obj_main = Csv2Table.new(csv_file, aligns)
obj_main.convert
rescue => e
STDERR.puts "[EXCEPTION] #{e}"
exit 1
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment