Class: ExcelToCsv::ExcelFile

Inherits:
Object
  • Object
show all
Defined in:
lib/exceltocsv/excel_file.rb

Constant Summary collapse

FORCE_WIN_OLE =
1

Instance Method Summary collapse

Constructor Details

#initializeExcelFile



28
29
30
31
32
# File 'lib/exceltocsv/excel_file.rb', line 28

def initialize()
  @date_RE = Regexp.new(/\d{4,4}\/\d{2,2}\/\d{2,2}/)
  @date_with_dashes_RE = Regexp.new(/\d{4,4}-\d{2,2}-\d{2,2}/)
  @date_with_time_RE = Regexp.new(/\d{2,2}:\d{2,2}:\d{2,2}/)
end

Instance Method Details

#clean_csv(filename) ⇒ Object



137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
# File 'lib/exceltocsv/excel_file.rb', line 137

def clean_csv(filename)
  max_row_length = 0
  CSV.foreach(filename) do |row|
    row_len = 0
    i = 0
    row.each do |item|
      row_len = i if !item.nil? && !item.empty?
      i += 1
    end
    max_row_length = row_len if row_len > max_row_length
  end

  puts "Max row length: #{max_row_length.to_s}" if verbose?

  tmp_file = filename.to_s + ".tmp.csv"
  CSV.open(tmp_file, "wb") do |tmp_csv|
    # Used to track empty lines
    empty_found = false

    CSV.foreach(filename) do |row|
      i = 0
      clean_row = []
      while(i <= max_row_length) do
        clean_row << row[i]
        i += 1
      end
      # We need to stop output on 2nd empty row
      break if empty_row?(clean_row) && empty_found
      empty_found = empty_row?(clean_row)
      tmp_csv << clean_row
    end # CSV read
  end # CSV write

  # Replace original file with tmpfile.
  FileUtils.rm filename
  FileUtils.mv tmp_file, filename
end

#clean_int_value(a_cell) ⇒ Object

If the result is n.000… Remove the unecessary zeros.



225
226
227
228
229
230
231
# File 'lib/exceltocsv/excel_file.rb', line 225

def clean_int_value(a_cell)
  if(a_cell.match(/\.[0]+$/))
    cary = a_cell.split(".")
    a_cell = cary[0]
  end
  a_cell
end

#empty_row?(row) ⇒ Boolean

Return true if row contains no data



176
177
178
179
180
181
182
# File 'lib/exceltocsv/excel_file.rb', line 176

def empty_row?(row)
  is_empty = true
  row.each do |item|
    is_empty = false if item && !item.empty?
  end
  is_empty
end

#format_date(a_cell) ⇒ Object

If the cell is a date, format it to MM/DD/YYYY, stripping time.



234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
# File 'lib/exceltocsv/excel_file.rb', line 234

def format_date(a_cell)
  isdate = true if(nil != (dt = a_cell.match(@date_RE)))
  isdate = true if(isdate || (nil != (dt = a_cell.match(@date_with_dashes_RE))) )
  isdate = true if(isdate || (nil != (dt = a_cell.match(@date_with_time_RE))) )
  if isdate
    begin
      mod_dt = DateTime.parse(a_cell)
      cary = "#{mod_dt.month}/#{mod_dt.day}/#{mod_dt.year}"
      if(true == verbose?)
        puts ""
        puts "*** Converted date to #{cary} ***"
        puts ""
      end
      a_cell = cary
    rescue ArgumentError => e
      # Either this is not a date, or the date format is unrecognized,
      # nothing to see here, moving on.
    end
  end
  a_cell
end

#prepare_outdir(outdir) ⇒ Object



256
257
258
259
260
# File 'lib/exceltocsv/excel_file.rb', line 256

def prepare_outdir(outdir)
  if( !File.directory?(outdir) )
    FileUtils.makedirs("#{outdir}")
  end
end

#process_cell_value(a_cell) ⇒ Object



184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
# File 'lib/exceltocsv/excel_file.rb', line 184

def process_cell_value(a_cell)
  # Truncate the number to 3 decimal places if numeric.
  a_cell = truncate_decimal(a_cell)

  # Remove leading and trailing spaces.
  a_cell = a_cell.to_s.strip

  # If the result is n.000... Remove the unecessary zeros.
  a_cell = clean_int_value(a_cell)

  # If the result is a date, remove time.
  a_cell = format_date(a_cell)

  # Surround the cell value with quotes when it contains a comma.
  a_cell = '"' + a_cell + '"' if a_cell.include?(',')

  a_cell
end

#set_flag(flg) ⇒ Object



47
48
49
50
51
# File 'lib/exceltocsv/excel_file.rb', line 47

def set_flag(flg)
  if (flg == "-v")
    @verbose = true
  end
end

#truncate_decimal(a_cell) ⇒ Object

Truncates a decimal to 3 decimal places if numeric and remove trailing zeros, if more than one decimal place. returns a string



206
207
208
209
210
211
212
213
214
215
# File 'lib/exceltocsv/excel_file.rb', line 206

def truncate_decimal(a_cell)
  if(a_cell.is_a?(Numeric))
    a_cell = truncate_decimal_to_string(a_cell, 3)
    # Truncate zeros (unless there is only 1 decimal place)
    # eg. 12.10 => 12.1
    #     12.0  => 12.0
    a_cell = BigDecimal.new(a_cell).to_s("F")
  end
  a_cell
end

#truncate_decimal_to_string(num, places) ⇒ Object

Truncates a decimal and converts it to a string. num: decimal to truncate places: number of decimal places to truncate at



220
221
222
# File 'lib/exceltocsv/excel_file.rb', line 220

def truncate_decimal_to_string(num, places)
  "%.#{places}f" % num
end

#verbose?Boolean



53
54
55
# File 'lib/exceltocsv/excel_file.rb', line 53

def verbose?()
  @verbose ||= false
end

#winPath(filepath) ⇒ Object



262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
# File 'lib/exceltocsv/excel_file.rb', line 262

def winPath(filepath)
  parts = filepath.split("/")
  mspath = nil

  for part in parts
    if(mspath == nil)
      mspath = []
      mspath << part
    else
      mspath << "\\" << part
    end
  end

  mspath
end

#xl_appObject



34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/exceltocsv/excel_file.rb', line 34

def xl_app
  return @xl_app unless @xl_app.nil?
  if OS.windows? and defined?(FORCE_WIN_OLE)
    require_relative 'win_excel'
    @xl_app = WinExcel.new
  else
    # CrossPlatformExcel is faster (like, by 30x).
    require_relative 'cross_platform_excel'
    @xl_app = CrossPlatformExcel.new
  end
  @xl_app
end

#xl_to_csv(infile, outfile) ⇒ Object

Convert the 1st sheet in an xls(x) file to a csv file.



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
# File 'lib/exceltocsv/excel_file.rb', line 58

def xl_to_csv(infile, outfile)
  filepath = File.expand_path(infile)
  puts "xl_to_csv: #{infile} => #{outfile}" if verbose?

  unless File.exists?(filepath)
    puts "Unable to find file."
    puts "  #{filepath}"
    return
  end

  #   Open an Excel file
  xl_app.open_workbook filepath

  # Build a list of work sheets to dump to file.
  sheets_in_file = []

  sheet_saved_count = 0

  xl_app.worksheet_names.each do |sheetname|
    if( sheetname.match(/CQDS/) || sheetname.match(/PLK/) )
      sheets_in_file << sheetname
      puts "Converting sheet #{sheetname}" if verbose?
      sheet_saved_count += 1
    end
  end

  if (1 > sheet_saved_count)
    puts "*** No sheets labeled 'PLK' or 'CQDS' ***"
    puts "Verify #{infile} is formatted correctly."
    # Close Excel
    xl_app.close_workbook
    return
  end

  # Write sheet data to file.
  File.open(outfile, "w") do |f|
    data = xl_app.worksheet_data(sheets_in_file[0])
    for row in data
      row_data = []
      for a_cell in row
        row_data << process_cell_value(a_cell)
      end

      contains_data = false

      # Determine if the row contains any data.
      for cell in row_data
        if(cell.match(/[^,\r\n]+/))
          contains_data = true
        end
      end

      # Insert an empty line if the row contains no data.
      if(true == contains_data)
        f << row_data.join(",")
        f << "\n"

        if(true == verbose?)
          puts "#{row_data}"
        end

      else
        f << "\n"

        if(true == verbose?)
          puts "\n"
        end
      end
    end
  end

  # Strip empty data from end of lines
  clean_csv(outfile)

  # Close Excel
  xl_app.close_workbook
end