Ruby Txt 轉為 CSV 通用的工具
require 'csv'namespace :sys_file_conver do desc "把txt資料匯入到csv中" task :txt_to_csv => :environment do amount = 100 head_hash = { '對賬檔案名稱' =>[12], '商戶號' =>[15], '商戶類型' => [4], '清算日期' => [8], '總比數' => [12], '總金額' => [15, amount], '支付總比數' => [12], '支付總金額' => [15, amount], '退款總比數' => [12], '退款總金額' => [15, amount], '撤銷總比數' => [12], '撤銷總金額' => [15, amount] } body_hash = { '清算日期' => [8], '入賬日期' => [8], '卡號' => [19], '交易類型' => [4], '交易金額' => [ 15, amount], '入賬金額' => [ 15, amount], '手續約金額' => [ 15, amount], '流水號' => [6], '交易日期時間' => [10], '終端號' => [8], '商戶號' => [15], '商戶類型' => [4], '受理機構號' => [6], '系統檢索號' => [12], '授權號' => [6], '渠道類型' => [2], '支付卡種' => [2], '訂單號' => [40] } txt_file_path = ENV['txt_file_path'] || "#{Rails.root}/tmp/txt_file.txt" csv_file_path = ENV['csv_file_path'] || "#{Rails.root}/tmp/csv_file.csv" File.new(csv_file_path) if FileTest::exists?(csv_file_path) CSV.open(csv_file_path,'w') do |data| data << hash_to_array_value(head_hash) txt_array = IO.readlines(txt_file_path, :encoding => 'GB2312') txt_array.each_with_index do |str,index| case index when 0 data << str_to_array_by_hash(str,head_hash) data << hash_to_array_value(body_hash) else data << str_to_array_by_hash(str,body_hash) end end end end# ----------------------------Hash to array------------------------------------def str_to_array_by_hash(str,hash) array = [] hash_to_array_value(hash, 1).inject(0){ |idx, code| str_code = str[idx,code[0]] str_code = str_code.to_f/code[1] unless code[1].blank? array << convert_gbk(str_code) idx+code[0] } arrayend# def hash_to_array_key(hash)# hash.inject([]){|a,d| a << convert_gbk(d[0])}# enddef hash_to_array_value(hash,i=0) hash.inject([]){|a,d| a << convert_gbk(d[i])}end# ---------------------------Convert util-------------------------------------- def convert(str)require 'iconv'beginconverter = Iconv.new("UTF-8", "GB2312")converter.iconv(str)rescuestrendenddef convert_gbk(str)require 'iconv'beginconverter = Iconv.new("GB2312", "UTF-8")converter.iconv(str)rescuestrendendend