Last active
June 20, 2020 19:06
-
-
Save lcguida/e1b88ada65e6cfb893edb427b8bc95d9 to your computer and use it in GitHub Desktop.
Ruby script to trasnform my father accounting excel in a formated CSV to later be trasnformed in OFX
This file contains hidden or 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 'rubyXL' | |
require 'rubyXL/convenience_methods' | |
require 'csv' | |
# Do not show gem warnings. See: https://github.com/weshatheleopard/rubyXL/blob/3fffae09589e7c7491243402aed2c473e4469107/lib/rubyXL/objects/relationships.rb#L85 | |
module RubyXL | |
@@suppress_warnings = true | |
end | |
if ARGV.size != 1 | |
puts <<~USAGE | |
Usage: to_csv <caminho_arquivo_xls> | |
USAGE | |
exit 1 | |
end | |
file_path = ARGV[0].strip | |
unless File.exist?(file_path) | |
puts "Arquivo #{file_path} não existe" | |
exit 1 | |
end | |
unless File.file?(file_path) | |
puts "Arquivo #{file_path} não existe" | |
exit 1 | |
end | |
puts "** Processando: #{File.basename(file_path)} **" | |
workbook = RubyXL::Parser.parse(file_path) | |
lines = [] | |
print " [*] Parsing file ... " | |
workbook.worksheets.each do |sheet| | |
date_str = sheet[2][1].value.match(/\d{2}\/\d{2}\/\d{4}/).to_s | |
date = Date.strptime(date_str, "%d/%m/%Y") | |
current_line = 5 # Venda do dia da loja (Linha 6, começando em 0) | |
loop do | |
description = sheet[current_line][0].value | |
break if description =~ /CAIXA FINAL/ || description.nil? | |
credit = sheet[current_line][1].value | |
debit = begin | |
value = sheet[current_line][2].value | |
value.nil? ? nil : value.to_f * -1 | |
end | |
value = [credit, debit].compact.first | |
if value.nil? | |
current_line += 1 | |
next | |
end | |
formatted_date = date.strftime('%m/%d/%Y') | |
lines << ['Caixa Físico Loja', formatted_date, description, description, value] | |
current_line += 1 | |
end | |
end | |
puts '[OK]' | |
print " [*] Genrarting CSV ..." | |
CSV.open('output.csv', 'w+', force_quotes: true, quote_empty: true) do |csv| | |
csv << %w[Account Date Description Memo Amount] # headers | |
lines.each { |line| csv << line } | |
end | |
puts '[OK]' | |
puts "Agora converte o arquivo em https://csvconverter.biz/" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment