Created
January 12, 2012 02:35
-
-
Save emartini/1598207 to your computer and use it in GitHub Desktop.
Create excel file from SQL query using mysql2 and spreadsheet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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