Skip to content

Instantly share code, notes, and snippets.

@emartini
Created January 12, 2012 02:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emartini/1598207 to your computer and use it in GitHub Desktop.
Save emartini/1598207 to your computer and use it in GitHub Desktop.
Create excel file from SQL query using mysql2 and spreadsheet
# How to create a excel file from any sql query
# @emartini86
# Based on basic documentation from required gems:
# https://github.com/brianmario/mysql2
# http://spreadsheet.rubyforge.org/file.GUIDE.html
require "rubygems"
require "mysql2"
require 'spreadsheet'
#connect to example MySQL sakila database
client = Mysql2::Client.new(:host => "localhost", :username => "root", :database=>"sakila")
qry_str = "SELECT * FROM `sakila`.`payment` limit 200;"
results = client.query(qry_str)
#prepare excel book:
book = Spreadsheet::Workbook.new
sheet1 = book.create_worksheet
#set headers from results:
xls_row = sheet1.row(0)
results.fields.each{|v| xls_row.push v }
#write the rows
results.each_with_index do |result,i|
xls_row = sheet1.row(i+1)
result.values.each{|v| xls_row.push v}
end
book.write 'file.xls'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment