Module: CsvTsvXlsxHandler

Defined in:
lib/csv_tsv_xlsx_handler.rb,
lib/csv_tsv_xlsx_handler/version.rb

Constant Summary collapse

VERSION =

Increment the patch version

"0.1.1"

Class Method Summary collapse

Class Method Details

.read_csv(file_path) ⇒ Object

Reads a CSV file and returns the data as an array of hashes



8
9
10
11
12
13
14
# File 'lib/csv_tsv_xlsx_handler.rb', line 8

def self.read_csv(file_path)
  result = []
  CSV.foreach(file_path, headers: true, encoding: 'UTF-8') do |row|
    result << row.to_hash
  end
  result
end

.read_tsv(file_path) ⇒ Object

Reads a TSV file and returns the data as an array of hashes



28
29
30
31
32
33
34
# File 'lib/csv_tsv_xlsx_handler.rb', line 28

def self.read_tsv(file_path)
  result = []
  CSV.foreach(file_path, headers: true, col_sep: "\t", encoding: 'UTF-8') do |row|
    result << row.to_hash
  end
  result
end

.read_xlsx(file_path) ⇒ Object

Reads an XLSX file and returns the data as an array of hashes



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/csv_tsv_xlsx_handler.rb', line 48

def self.read_xlsx(file_path)
  result = []
  workbook = RubyXL::Parser.parse(file_path)
  worksheet = workbook[0] # Accessing the first sheet

  headers = worksheet[0].cells.map(&:value) # First row as headers

  worksheet.each_with_index do |row, index|
    next if index == 0  # Skip the header row
    row_hash = Hash[headers.zip(row.cells.map { |cell| cell.value.to_s.encode('UTF-8') })]
    result << row_hash
  end

  result
end

.write_csv(file_path, data) ⇒ Object

Writes data to a CSV file



17
18
19
20
21
22
23
24
25
# File 'lib/csv_tsv_xlsx_handler.rb', line 17

def self.write_csv(file_path, data)
  CSV.open(file_path, "wb", encoding: 'UTF-8') do |csv|
    # Write headers (assuming the first row contains the keys)
    csv << data.first.keys
    data.each do |row|
      csv << row.values
    end
  end
end

.write_tsv(file_path, data) ⇒ Object

Writes data to a TSV file



37
38
39
40
41
42
43
44
45
# File 'lib/csv_tsv_xlsx_handler.rb', line 37

def self.write_tsv(file_path, data)
  CSV.open(file_path, "wb", col_sep: "\t", encoding: 'UTF-8') do |csv|
    # Write headers (assuming the first row contains the keys)
    csv << data.first.keys
    data.each do |row|
      csv << row.values
    end
  end
end

.write_xlsx(file_path, data) ⇒ Object

Writes data to an XLSX file



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/csv_tsv_xlsx_handler.rb', line 65

def self.write_xlsx(file_path, data)
  workbook = RubyXL::Workbook.new
  worksheet = workbook[0]

  # Write headers (first row)
  headers = data.first.keys
  worksheet.add_row(headers)

  # Write data (remaining rows)
  data.each do |row|
    worksheet.add_row(row.values.map { |value| value.to_s.encode('UTF-8') })
  end

  workbook.write(file_path)
end