Created
February 13, 2012 15:45
-
-
Save bycoffe/1817709 to your computer and use it in GitHub Desktop.
Create an XLS spreadsheet from an electronic FEC filing, using Fech
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
require 'fech' | |
require 'spreadsheet' | |
module Fech | |
class Filing | |
# Create an XLS spreadsheet from a filing. | |
def as_xls(filename=nil) | |
spreadsheet = Spreadsheet::Workbook.new | |
bold = Spreadsheet::Format.new :weight => :bold | |
# Create an ordered list of unique field types | |
form_types = [] | |
# And a hash of {form_type: [rows]} | |
filing_data = {} | |
each_row do |row| | |
form_type = row[0] | |
form_types << form_type unless form_types.include?(form_type) | |
filing_data[form_type] = [] unless filing_data.include?(form_type) | |
filing_data[form_type] << row | |
end | |
form_types.each_with_index do |form_type, idx| | |
form_headers = map_for(form_type) | |
# Create the worksheet for this form type | |
worksheet = spreadsheet.create_worksheet(:name => form_type) | |
worksheet.row(0).default_format = bold | |
form_headers.each_with_index do |hdr, idx| | |
# row 0, cell idx (cells are 0-indexed) | |
worksheet[0, idx] = hdr.to_s | |
end | |
filing_data[form_type].each_with_index do |row, row_idx| | |
row_idx += 1 # add 1 to start 1 row below header | |
row.each_with_index do |val, cell_idx| | |
worksheet[row_idx, cell_idx] = val | |
end | |
end | |
end | |
filename ||= "#{filing_id}.xls" | |
spreadsheet.write(filename) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment