Module: RubyXlsxToMd

Defined in:
lib/ruby_xlsx_to_md.rb,
lib/ruby_xlsx_to_md/version.rb,
lib/ruby_xlsx_to_md/encoding.rb

Defined Under Namespace

Modules: Encoding Classes: Error

Constant Summary collapse

VERSION =
"0.1.0"

Class Method Summary collapse

Class Method Details

.col_letter(index) ⇒ Object



57
58
59
60
61
62
63
64
65
# File 'lib/ruby_xlsx_to_md.rb', line 57

def self.col_letter(index)
  letters = ""
  loop do
    letters = ((65 + (index % 26)).chr) + letters
    index = index / 26 - 1
    break if index < 0
  end
  letters
end

.convert(path) ⇒ Object



11
12
13
14
15
16
17
# File 'lib/ruby_xlsx_to_md.rb', line 11

def self.convert(path)
  workbook = RubyXL::Parser.parse(path)

  workbook.worksheets.map do |sheet|
    "---\n#{sheet.sheet_name}\n---\n#{sheet_to_markdown(sheet)}"
  end.join("\n\n")
end

.sheet_to_markdown(sheet) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/ruby_xlsx_to_md.rb', line 19

def self.sheet_to_markdown(sheet)
  rows = sheet.sheet_data
  min_c = nil ; max_c = nil

  # Find column range across all rows
  rows.rows.each_with_index do |row, _ri|
    next if row.nil?
    row.cells.each_with_index do |cell, ci|
      next if cell.nil? || (cell.value.nil? || cell.value.to_s.strip.empty?)
      min_c = ci if min_c.nil? || ci < min_c
      max_c = ci if max_c.nil? || ci > max_c
    end
  end

  return "" if min_c.nil?

  lines = []

  header = "| Row # |"
  (min_c..max_c).each { |c| header += " #{col_letter(c)} |" }
  lines << header

  sep = "|---|"
  (min_c..max_c).each { |_| sep += "---|" }
  lines << sep

  rows.rows.each_with_index do |row, ri|
    vals = (min_c..max_c).map do |ci|
      raw = row&.[](ci)&.value
      val = raw.to_s.empty? ? "" : Encoding.ensure_utf8(raw.to_s)
      val.include?("|") ? val.gsub("|", "\\|") : val
    end
    lines << "| #{ri + 1} | #{vals.join(" | ")} |"
  end

  lines.join("\n")
end