Fork me on GitHub

Project Notes

#312 CSV to Markdown Tables (Ruby)

How to convert comma-separated value data into markdown tables with ruby.

Notes

Converting CSV files to Markdown tables is a pretty common task I encounter, especially when generating documentation. The CSV data may come from a report, spreadsheet, or database extract, and I want to include it as a correctly formatted markdown table.

See python/csv2md for how to do this with python scripts, command line utilities, online tools, and editor extensions.

These notes provide some ruby alternatives.

To test options, I’m using a listing of the Sharpe novels by Bernard Cornwell: sharpe.csv.

csv2md gem

The csv2md gem provides a command line utility for converting csv formatted data to a GitHub Flavored Markdown table.

Example usage:

cd using_csv2md
gem install bundler
bundle install
csv2md ../sharpe.csv > README.md

See the raw output here and the rendered markdown output here.

Custom Ruby Script

Uses csv to read the input file and generate markdown. See the csv2md.rb script. The essence of the conversion is in these few lines:

def csv_to_markdown(file)
  table = CSV.read(file)
  markdown = ""
  markdown << "| " + table[0].join(" | ") + " |\n"
  markdown << "|" + (" --- |" * table[0].size) + "\n"
  table[1..-1].each do |row|
    markdown << "| " + row.join(" | ") + " |\n"
  end
  markdown
end

Example usage:

cd using_custom_script
gem install bundler
bundle install
ruby csv2md.rb ../sharpe.csv > README.md

See the raw output here and the rendered markdown output here.

Credits and References

  • python/csv2md - using python scripts, command line utilities, online tools, and editor extensions
  • csv2md
About LCK#312 rubymarkdowncsv

This page is a web-friendly rendering of my project notes shared in the LittleCodingKata GitHub repository.

Project Source on GitHub Return to the LittleCodingKata Catalog
About LittleCodingKata

LittleCodingKata is my collection of programming exercises, research and code toys broadly spanning things that relate to programming and software development (languages, frameworks and tools).

These range from the trivial to the complex and serious. Many are inspired by existing work and I'll note credits and references where applicable. The focus is quite scattered, as I variously work on things new and important in the moment, or go back to revisit things from the past.

This is primarily a personal collection for my own edification and learning, but anyone who stumbles by is welcome to borrow, steal or reference the work here. And if you spot errors or issues I'd really appreciate some feedback - create an issue, send me an email or even send a pull-request.

Follow the Blog follow projects and notes as they are published in your favourite feed reader