Created
April 9, 2020 05:23
-
-
Save misshie/875c06df26550e83f900b7a3b29a8c8b to your computer and use it in GitHub Desktop.
A Ruby script conveting a tab delimited text file into an Excel XLSX file using the RubyXL library https://github.com/weshatheleopard/rubyXL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require 'optparse' | |
require 'fileutils' | |
require 'rubyXL' | |
require 'rubyXL/convenience_methods/cell' | |
require 'rubyXL/convenience_methods/color' | |
require 'rubyXL/convenience_methods/font' | |
require 'rubyXL/convenience_methods/workbook' | |
require 'rubyXL/convenience_methods/worksheet' | |
class Tab2Xl | |
attr_reader :opts | |
def initialize(opts) | |
@opts = opts | |
end | |
def delim2xlsx(pathin, pathout) | |
open(pathin, "r") do |fin| | |
wb = RubyXL::Workbook.new | |
ws = wb[0] | |
fin.each_line.with_index do |row, nrow| | |
ws.change_row_height(nrow, 18.75) | |
ws.change_row_font_name(nrow, "Segoe UI") | |
ws.change_row_font_size(nrow, 11) | |
row.chomp.split("\t").each_with_index do |col, ncol| | |
case col | |
when /^\d+$/ | |
ws.add_cell(nrow, ncol, Integer(col)) | |
when /^\d+(?:\.\d+)?$/ | |
ws.add_cell(nrow, ncol, Float(col)) | |
else | |
ws.add_cell(nrow, ncol, col) | |
end | |
end | |
end | |
wb.write(pathout) | |
end | |
end | |
def run | |
if ARGV[0] =~ /\..*$/ | |
out = ARGV[0].sub(/\..*$/, ".xlsx") | |
else | |
out = ARGV[0] + ".xlsx" | |
end | |
delim2xlsx("#{ARGV[0]}", "#{out}") | |
end | |
end | |
if $0 == __FILE__ | |
opts = ARGV.getopts("h") | |
Tab2Xl.new(opts.map{|k,v|[k.to_sym, v]}.to_h).run | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment