rubyxls 1.0.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 565163dadd728164052abd601e382f4edc0f34fb
4
+ data.tar.gz: 8e2cf098733fbc299deab62a41eb9a85b81d33e2
5
+ SHA512:
6
+ metadata.gz: 025c18aa1dbcd9e72bc8233ae09bc58a6c584097e0483248d9d2a2feeb045177ca10d4b86af5047ebf131552b1c6b04e0cd87dde5d0c04f7bc3e1efd03c3ae2a
7
+ data.tar.gz: 1303c010b7a56eb4a517525fba5a629d51a922c957bb76c038900a8726ff57d960cf62226d3ae4a691ccc36b3b957f6be0f6d209e7048670ccca63e56306b68c
@@ -0,0 +1,9 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --format documentation
2
+ --color
@@ -0,0 +1,49 @@
1
+ # Contributor Code of Conduct
2
+
3
+ As contributors and maintainers of this project, and in the interest of
4
+ fostering an open and welcoming community, we pledge to respect all people who
5
+ contribute through reporting issues, posting feature requests, updating
6
+ documentation, submitting pull requests or patches, and other activities.
7
+
8
+ We are committed to making participation in this project a harassment-free
9
+ experience for everyone, regardless of level of experience, gender, gender
10
+ identity and expression, sexual orientation, disability, personal appearance,
11
+ body size, race, ethnicity, age, religion, or nationality.
12
+
13
+ Examples of unacceptable behavior by participants include:
14
+
15
+ * The use of sexualized language or imagery
16
+ * Personal attacks
17
+ * Trolling or insulting/derogatory comments
18
+ * Public or private harassment
19
+ * Publishing other's private information, such as physical or electronic
20
+ addresses, without explicit permission
21
+ * Other unethical or unprofessional conduct
22
+
23
+ Project maintainers have the right and responsibility to remove, edit, or
24
+ reject comments, commits, code, wiki edits, issues, and other contributions
25
+ that are not aligned to this Code of Conduct, or to ban temporarily or
26
+ permanently any contributor for other behaviors that they deem inappropriate,
27
+ threatening, offensive, or harmful.
28
+
29
+ By adopting this Code of Conduct, project maintainers commit themselves to
30
+ fairly and consistently applying these principles to every aspect of managing
31
+ this project. Project maintainers who do not follow or enforce the Code of
32
+ Conduct may be permanently removed from the project team.
33
+
34
+ This code of conduct applies both within project spaces and in public spaces
35
+ when an individual is representing the project or its community.
36
+
37
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
38
+ reported by contacting a project maintainer at alexxander.frankel@gmail.com. All
39
+ complaints will be reviewed and investigated and will result in a response that
40
+ is deemed necessary and appropriate to the circumstances. Maintainers are
41
+ obligated to maintain confidentiality with regard to the reporter of an
42
+ incident.
43
+
44
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
45
+ version 1.3.0, available at
46
+ [http://contributor-covenant.org/version/1/3/0/][version]
47
+
48
+ [homepage]: http://contributor-covenant.org
49
+ [version]: http://contributor-covenant.org/version/1/3/0/
data/Gemfile ADDED
@@ -0,0 +1,3 @@
1
+ source 'https://rubygems.org'
2
+
3
+ gemspec
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2016 Alexander Frankel
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
@@ -0,0 +1,227 @@
1
+ # Rubyxls
2
+
3
+ Generate XLS files using ruby. Rubyxls provides a simple DSL :o express anything from simple ruby strings to complex Active Record models.
4
+ Support for multi-sheet workbooks, chart generation, and formula based cells included.
5
+
6
+ ## Installation
7
+
8
+ Add this line to your application's Gemfile:
9
+
10
+ ```ruby
11
+ gem 'rubyxls'
12
+ ```
13
+
14
+ And then execute:
15
+
16
+ $ bundle
17
+
18
+ Or install it yourself as:
19
+
20
+ $ gem install rubyxls
21
+
22
+ ## Usage
23
+
24
+ ### Components
25
+ After installing, Rubyxls is easy to use.
26
+
27
+ Rubyxls has the same components of an actual excel spreadsheet, abstracting away the messy details.
28
+
29
+ I like to think of the components in the following way:
30
+ - **Report**: has_many workbooks (yes, a report can have many workbooks resulting in a zip file of all the workbooks)
31
+ - **Workbook**: has_many sheets (when creating a new workbook, you are essentially creating a new xls file)
32
+ - **Sheet**: has_many view models (tables)
33
+ - **View Model (Table)**: this is where all of the data goes. More on ViewModels to come...
34
+ - **Style Manager**: create re-usable styles to make sure your reports are beautiful and consistent.
35
+
36
+ **Please don't be fooled by the has_many term listed above. This has nothing to do with ActiveRecord or any database relation. As a ruby/rails developer, I have just gotten in the habit of using this association terminology to describe any kind of relationship : )**
37
+
38
+ In order to create your very own excel report, all you have to do is inherit each component's functionality that Rubyxls gives you.
39
+
40
+ **Note: Rubyxls is built with the intention that you will include each of the listed components in your excel project, allowing each component to play nicely with each other.**
41
+
42
+ #### Report
43
+ ```ruby
44
+ class YourVeryOwnReport < Rubyxls::Report
45
+
46
+ def initialize(whatever_data_you_need)
47
+ @data = whatever_data_you_need
48
+ super() # Call #super with no parameters
49
+ end
50
+
51
+ private
52
+
53
+ def build_workbooks!
54
+ @workbooks << YourVeryOwnWorkbook.new(whatever_data_you_need)
55
+ end
56
+ end
57
+ ```
58
+ - **Inherit from Rubyxls::Report** - this will give you all the functionality a report needs to build itself.
59
+ - **Call super() in #initialize** - this will create an instance variable `@workbooks` to hold all of the beautfiul workbooks you are about to create!
60
+ - **#build_workbooks!** - append any workbooks that you create into `@workbooks` so that your report "has_many" workbooks just like the real excel!
61
+
62
+ #### Workbook
63
+ ```ruby
64
+ class YourVeryOwnWorkbook < Rubyxls::Workbook
65
+
66
+ def initialize(whatever_data_you_neeed)
67
+ @data = whatever_data_you_need
68
+ super(name: "your_very_own_workbook") # Call #super passing in only a name parameter
69
+ end
70
+
71
+ private
72
+
73
+ def build_sheets!
74
+ @sheets << YourVeryOwnSheet.new(whatever_data_you_need)
75
+ end
76
+
77
+ end
78
+ ```
79
+ - **Inherit from Rubyxls::Workbook** - get all of that groovy (not the programming language) functionality that Rubyxls gives your Workbook.
80
+ - **Call super() in #initialize passing in a "name" parameter** - this will create an instance variable `@sheets` to hold all of your sheets and will name the workbook you are creating.
81
+ - **#build_sheets!** - append any sheets that you create into `@sheets` so that your workbook "has_many" sheets!
82
+
83
+ #### Sheet
84
+ ```ruby
85
+ class YourVeryOwnSheet < Rubyxls::Sheet
86
+
87
+ def initialize(whatever_data_you_need)
88
+ @data = whatever_data_you_need
89
+ super(sheet_name: "YourVeryOwnSheet") # Call #super passing in only a sheet_name parameter
90
+ end
91
+
92
+ private
93
+
94
+ def build_cells
95
+ Rubyxls::Builders::CellBuilder.new(model_data_rows: YourVeryOwnViewModel.new(title: "Your Very Own View Model").data_rows, start_row: 1, start_column: "A").cells
96
+ .+ Rubyxls::Builders::CellBuilder.new(model_data_rows: AnotherViewModel.new(title: "Another View Model").data_rows, start_row: 4, start_column: "L").cells
97
+ end
98
+
99
+ end
100
+ ```
101
+ - **Inherit from Rubyxls::Sheet** - gotta get that sheet functionality
102
+ - **Call super() in #initialize passing in a "name" parameter** - this will give your sheet a name
103
+ - **#build_cells!** - this is the dumping ground for all of your data. The CellBuilder, which takes in a view model as a parameter will break apart your view models / tables into invidual
104
+ cells and organize them properly. Don't forget to specify where on the sheet you would like your view models to be drawn using `start_row` and `start_column`!
105
+ Behind the scenes, we are taking all of your modularized view models, breaking them apart into individual cells, throwing all of those cells into one LARGE pot and re-arranging them in the
106
+ proper order. Cool, huh!
107
+
108
+ #### ViewModel
109
+ ```ruby
110
+ class YourVeryOwnViewModel < Rubyxls::ViewModel
111
+
112
+ def initialize(whatever_data_you_need)
113
+ @data = whatever_data_you_need
114
+ super() # Call #super passing in no parameters
115
+ end
116
+
117
+ private
118
+
119
+ def build_data_rows!
120
+ @data_rows << [
121
+ { value: "Title Row", style: [:bold] }
122
+ ]
123
+ end
124
+
125
+ end
126
+ ```
127
+ - **Inherit from Rubyxls::ViewModel**
128
+ - **Call super() in #initialize passing**
129
+ - **#build_data_rows!** - this is where you decide what data goes into the workbook and how it looks. Let's break it down by describing the ruby version of each excel component that makes up a row.
130
+ ```
131
+ | Ruby | Excel | Desciption |
132
+ | ----- ------- ------------------------------------------------------ |
133
+ | Array | Row | Each array has lots of individual cells or ruby hashes |
134
+ | Hash | Cell | Each cell has a value and a style |
135
+ ```
136
+
137
+ `@data_rows` starts as an empty array that is defined when you call `super()` in the initialize method. The whole idea behind the View Model is to populate `@data_rows` with ruby arrays, each
138
+ representing a row in excel. Each ruby array is filled with ruby hashes, representing an individual cell.
139
+
140
+ Each individual cell is structured as follows:
141
+ ```ruby
142
+ { value: <any value>, style: [<list of styles to apply to this cell>] }
143
+ ```
144
+ A list of default styles is provided below!
145
+
146
+ ### Styling
147
+ #### Default Styles
148
+ - :bold
149
+ - :italic
150
+ - :underline
151
+ - :strike
152
+ - :indent
153
+ - :left_align
154
+ - :right_align
155
+ - :center_align
156
+ - :top_align
157
+ - :bottom_align
158
+ - :middle_align
159
+ - :border_right
160
+ - :boder_left
161
+ - :boder_top
162
+ - :boder_bottom
163
+ - :boder_all
164
+ - :number
165
+ - :decimal
166
+ - :date
167
+ - :time
168
+ - :currency
169
+ - :currency_precision
170
+ - :percent
171
+ - :wrap_text
172
+
173
+ #### Custom Styles
174
+ ``` ruby
175
+ class YourVeryOwnCustomStyleManager < Rubyxls::StyleManager
176
+
177
+ GREY = 'CCCCCC'
178
+
179
+ def initialize
180
+ super # Call super
181
+ end
182
+
183
+ private
184
+
185
+ def initialize_base_styles!
186
+ define_style(style: :medium, attributes: { sz: 12 })
187
+ define_style(style: :large, attributes: { sz: 14 })
188
+ define_style(style: :total_row, attributes: { b: true, bg_color: GREY })
189
+ super
190
+ end
191
+
192
+ end
193
+ ```
194
+ - **Inherit from Rubyxls::StyleManager**
195
+ - **Call super in #initialize passing** - in order to get all of those default styles that Rubyxls provides.
196
+ - **#initialize_base_styles!** - define your own styles according the the excel specification. Each style only needs a set of attributes.
197
+
198
+ Now you can apply your newly defined styles inside of any sheet.
199
+
200
+ **Note: in order to use user-defined styles, you must specify which style manager you would like to use when creating your sheet.**
201
+ ```ruby
202
+ class YourVeryOwnSheet
203
+
204
+ def initialize(data)
205
+ @data = data
206
+ super(sheet_name: "YourVeryOwnSheet", style_manager: YourVeryOwnCustomStyleManager.new)
207
+ end
208
+
209
+ end
210
+ ```
211
+ Now you will have access to your user-defined styles and the default styles that ship with Rubyxls!
212
+
213
+ ## Development
214
+
215
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
216
+
217
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
218
+
219
+ ## Contributing
220
+
221
+ Bug reports and pull requests are welcome on GitHub at https://github.com/alexanderfrankel/rubyxls. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
222
+
223
+
224
+ ## License
225
+
226
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
227
+
@@ -0,0 +1,5 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+ task :default => :spec
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "rubyxls"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "rubyxls"
5
+
6
+ default_report = Rubyxls.generate_default_report
7
+ Rubyxls.write_report_to_tmp(default_report)
8
+ Rubyxls.open(default_report)
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,8 @@
1
+ machine:
2
+
3
+ timezone:
4
+ America/New_York
5
+
6
+ ruby:
7
+ version:
8
+ 2.3.0
@@ -0,0 +1,43 @@
1
+ module Rubyxls
2
+
3
+ def self.generate_default_report
4
+ Report.new
5
+ end
6
+
7
+ def self.write_report_to_tmp(report)
8
+ file_path = report_tmp_file_path(report)
9
+ FileUtils.mkdir_p(tmp_dir_path) unless File.directory?(tmp_dir_path)
10
+ File.delete(file_path) if File.exist?(file_path)
11
+ File.open(file_path, 'w') do |file|
12
+ file << report.download!.read
13
+ end
14
+ end
15
+
16
+ def self.open(report)
17
+ `open "#{report_tmp_file_path(report)}"`
18
+ end
19
+
20
+ private
21
+
22
+ def self.tmp_dir_path
23
+ File.expand_path('../../tmp', __FILE__)
24
+ end
25
+
26
+ def self.report_tmp_file_path(report)
27
+ tmp_dir_path + "/#{report.file_name}.#{report.file_extension}"
28
+ end
29
+
30
+ end
31
+
32
+ require 'rubyxls/version'
33
+
34
+ require 'rubyxls/report'
35
+ require 'rubyxls/sheet'
36
+ require 'rubyxls/style_manager'
37
+ require 'rubyxls/view_model'
38
+ require 'rubyxls/workbook'
39
+
40
+ require 'rubyxls/builders/cell_builder'
41
+ require 'rubyxls/builders/chart_builder'
42
+ require 'rubyxls/builders/formula_builder'
43
+ require 'rubyxls/builders/row_builder'
@@ -0,0 +1,39 @@
1
+ module Rubyxls
2
+ module Builders
3
+ class CellBuilder
4
+
5
+ attr_reader :cells
6
+
7
+ def initialize(**opts)
8
+ @model_data_rows = opts.fetch(:model_data_rows)
9
+ @start_row = opts.fetch(:start_row, 1)
10
+ @start_column = opts.fetch(:start_column, "A")
11
+ @cells = []
12
+ build_cells!
13
+ end
14
+
15
+ private
16
+
17
+ def build_cells!
18
+ assign_row_column!
19
+ @cells = @model_data_rows.flatten
20
+ end
21
+
22
+ def assign_row_column!
23
+ @model_data_rows.each_with_index do |data_row, table_row_index|
24
+ data_row.each_with_index do |data_cell, table_column_index|
25
+ data_cell[:row] = @start_row + table_row_index
26
+ data_cell[:column] = retrieve_cell_column_letter(@start_column, table_column_index)
27
+ end
28
+ end
29
+ end
30
+
31
+ def retrieve_cell_column_letter(start_column, table_column_index)
32
+ cell_column = start_column.clone
33
+ table_column_index.times { cell_column.next! }
34
+ cell_column
35
+ end
36
+
37
+ end
38
+ end
39
+ end
@@ -0,0 +1,39 @@
1
+ require 'axlsx'
2
+
3
+ module Rubyxls
4
+ module Builders
5
+ class ChartBuilder
6
+
7
+ attr_reader :type
8
+ attr_reader :start_at
9
+ attr_reader :end_at
10
+ attr_reader :title
11
+ attr_reader :rot_x
12
+ attr_reader :rot_y
13
+ attr_reader :show_legend
14
+ attr_reader :bar_dir
15
+ attr_reader :cat_axis_title
16
+ attr_reader :val_axis_title
17
+ attr_reader :cat_axis_gridlines
18
+ attr_reader :val_axis_gridlines
19
+ attr_reader :series
20
+
21
+ def initialize(**opts)
22
+ @type = opts.fetch(:type, Axlsx::Bar3DChart)
23
+ @start_at = opts.fetch(:start_at, "A1")
24
+ @end_at = opts.fetch(:end_at, "A1")
25
+ @title = opts.fetch(:title, " ")
26
+ @rot_x = opts.fetch(:rot_x, 30)
27
+ @rot_y = opts.fetch(:rot_y, 20)
28
+ @show_legend = opts.fetch(:show_legend, false)
29
+ @bar_dir = opts.fetch(:bar_dir, :col)
30
+ @cat_axis_title = opts.fetch(:cat_axis_title, " ")
31
+ @val_axis_title = opts.fetch(:val_axis_title, " ")
32
+ @cat_axis_gridlines = opts.fetch(:cat_axis_gridlines, false)
33
+ @val_axis_gridlines = opts.fetch(:val_axis_gridlines, false)
34
+ @series = opts.fetch(:series, [])
35
+ end
36
+
37
+ end
38
+ end
39
+ end
@@ -0,0 +1,60 @@
1
+ module Rubyxls
2
+ module Builders
3
+ class FormulaBuilder
4
+
5
+ attr_reader :cells
6
+
7
+ def initialize(**opts)
8
+ @value = opts.fetch(:value, nil)
9
+ @style = opts.fetch(:style, [:default])
10
+ @width = opts.fetch(:width, nil)
11
+ @height = opts.fetch(:height, nil)
12
+ @data_validation = opts.fetch(:data_validation, nil)
13
+ @merge = opts.fetch(:merge, nil)
14
+ @fill = opts.fetch(:fill, :right)
15
+ @num_cells = opts.fetch(:num_cells, nil)
16
+ @row_index = opts.fetch(:row_index, nil)
17
+ @cells = []
18
+
19
+ fill_right! if @fill == :right
20
+ fill_down! if @fill == :down
21
+ fill_all! if @fill == :all
22
+ end
23
+
24
+ private
25
+
26
+ def fill_right!
27
+ raise "Num cells cannot be nil when filling right for formula: #{@value}!" if @num_cells.nil?
28
+ @num_cells.times do
29
+ add_cell!
30
+ shift_value_right!
31
+ end
32
+ end
33
+
34
+ def fill_down!
35
+ raise "Row index cannot be nil when filling down for formula: #{@value}!" if @row_index.nil?
36
+ shift_value_down!
37
+ add_cell!
38
+ end
39
+
40
+ def fill_all!
41
+ raise "Both num cells & row index cannot be nil when filling all for formula: #{@value}!" if @num_cells.nil? || @row_index.nil?
42
+ shift_value_down!
43
+ fill_right!
44
+ end
45
+
46
+ def add_cell!
47
+ @cells << { value: @value.nil? ? nil : @value.clone, style: @style, width: @width, height: @height, data_validation: @data_validation, merge: @merge }
48
+ end
49
+
50
+ def shift_value_right!
51
+ @value.nil? ? nil : @value.gsub!(/(?<![\$A-Z])[A-Z]+(?=[\$\d])/) { |column| column.next }
52
+ end
53
+
54
+ def shift_value_down!
55
+ @value.nil? ? nil : @value.gsub!(/(?<=[A-Z])[0-9]+/) { |row| row.to_i + @row_index }
56
+ end
57
+
58
+ end
59
+ end
60
+ end
@@ -0,0 +1,50 @@
1
+ module Rubyxls
2
+ module Builders
3
+ class RowBuilder
4
+
5
+ attr_reader :rows
6
+
7
+ def initialize(cells)
8
+ @cells = cells
9
+ @bottom_row_bound = 0
10
+ @right_column_bound = 0
11
+ expand_bottom_row_bound
12
+ expand_right_column_bound
13
+ @rows = Array.new(@bottom_row_bound) { Array.new(@right_column_bound) { { value: nil, style: [] } } }
14
+ build_rows!
15
+ end
16
+
17
+ private
18
+
19
+ def expand_bottom_row_bound
20
+ @cells.each do |cell|
21
+ @bottom_row_bound = cell[:row] if cell[:row] > @bottom_row_bound
22
+ end
23
+ end
24
+
25
+ def expand_right_column_bound
26
+ @cells.each do |cell|
27
+ @right_column_bound = convert_cell_column_to_integer(cell[:column]) if convert_cell_column_to_integer(cell[:column]) > @right_column_bound
28
+ end
29
+ end
30
+
31
+ def convert_cell_column_to_integer(cell_column)
32
+ offset = "A".ord - 1
33
+ cell_column.chars.inject(0) { |sum,char| sum * 26 + char.ord - offset }
34
+ end
35
+
36
+ def build_rows!
37
+ @cells.each { |cell| @rows[retrieve_cell_row_index(cell[:row])][retrieve_cell_column_index(cell[:column])] = cell }
38
+ end
39
+
40
+ def retrieve_cell_row_index(cell_row)
41
+ cell_row - 1
42
+ end
43
+
44
+ def retrieve_cell_column_index(cell_column)
45
+ convert_cell_column_to_integer(cell_column) - 1
46
+ end
47
+
48
+ end
49
+ end
50
+ end
@@ -0,0 +1,48 @@
1
+ module Rubyxls
2
+ class Report
3
+
4
+ attr_reader :workbooks
5
+ attr_reader :file_name
6
+
7
+ def initialize
8
+ @workbooks = []
9
+ @file_name = 'rubyxls'
10
+ build_workbooks!
11
+ end
12
+
13
+ def download!
14
+ if @workbooks.size == 1
15
+ @workbooks.first.to_stream
16
+ else
17
+ stream = StringIO.new
18
+ zipfile = Zip::File.new(stream, true, true)
19
+ @workbooks.each do |workbook|
20
+ zipfile.get_output_stream(workbook.filename) { |zipstream| IO.copy_stream(workbook.to_stream, zipstream) }
21
+ end
22
+ zipfile.write_buffer(stream)
23
+ zipfile.glob('*', &:clean_up)
24
+ stream.rewind
25
+ stream
26
+ end
27
+ end
28
+
29
+ def file_extension
30
+ @workbooks.size > 1 ? :zip : :xlsx
31
+ end
32
+
33
+ def content_type
34
+ if file_extension == :xlsx
35
+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
36
+ elsif file_extension == :zip
37
+ 'application/zip'
38
+ end
39
+ end
40
+
41
+ private
42
+
43
+ def build_workbooks!
44
+ @workbooks << Rubyxls::Workbook.new
45
+ end
46
+
47
+ end
48
+ end
@@ -0,0 +1,82 @@
1
+ module Rubyxls
2
+ class Sheet
3
+
4
+ FIT_TO_WIDTH = 1
5
+ ORIENTATION = :landscape
6
+ GRID_LINES = false
7
+ PAGE_MARGIN_TOP = 0.3
8
+ PAGE_MARGIN_LEFT = 0.3
9
+ PAGE_MARGIN_BOTTOM = 0.3
10
+ PAGE_MARGIN_RIGHT = 0.3
11
+ HEADER = 0.0
12
+ FOOTER = 0.0
13
+ LETTER_PAPER_SIZE = 1
14
+
15
+ attr_reader :sheet_name
16
+
17
+ def initialize(**opts)
18
+ @sheet_name = opts.fetch(:sheet_name, "Default Sheet")
19
+ @style_manager = opts.fetch(:style_manager, Rubyxls::StyleManager.new)
20
+ @paper_size = opts.fetch(:paper_size, LETTER_PAPER_SIZE)
21
+ end
22
+
23
+ def build_options(*taken_names)
24
+ { page_setup: build_page_setup,
25
+ print_options: build_print_options,
26
+ page_margins: build_page_margins,
27
+ name: unique_sheet_name(sanitize_sheet_name(@sheet_name), taken_names) }
28
+ end
29
+
30
+ def build_rows
31
+ Rubyxls::Builders::RowBuilder.new(build_cells).rows.each do |row|
32
+ row.each do |cell|
33
+ cell[:style] = @style_manager.retrieve_style_attributes(cell[:style])
34
+ end
35
+ end
36
+ end
37
+
38
+ def build_charts
39
+ []
40
+ end
41
+
42
+ def build_width_normalization
43
+ {}
44
+ end
45
+
46
+ private
47
+
48
+ def build_page_setup
49
+ { fit_to_width: FIT_TO_WIDTH,
50
+ orientation: ORIENTATION,
51
+ paper_size: @paper_size }
52
+ end
53
+
54
+ def build_print_options
55
+ { grid_lines: GRID_LINES }
56
+ end
57
+
58
+ def build_page_margins
59
+ { top: PAGE_MARGIN_TOP,
60
+ left: PAGE_MARGIN_LEFT,
61
+ bottom: PAGE_MARGIN_BOTTOM,
62
+ right: PAGE_MARGIN_RIGHT,
63
+ header: HEADER,
64
+ footer: FOOTER }
65
+ end
66
+
67
+ def build_cells
68
+ Rubyxls::Builders::CellBuilder.new(model_data_rows: Rubyxls::ViewModel.new(title_row: true, header_row: true, additional_rows: 1, total_row: true).data_rows, start_row: 2, start_column: "B").cells
69
+ end
70
+
71
+ def sanitize_sheet_name(sheet_name)
72
+ sheet_name.gsub(/[:\[\]\/\\\*\?]/, '-')
73
+ end
74
+
75
+ def unique_sheet_name(sheet_name, taken_names, index=1)
76
+ return sheet_name[0, 31] unless taken_names.include?(sheet_name[0, 31])
77
+ sheet_name = "#{sheet_name[0, 29 - index.to_s.length]}(#{index})"
78
+ unique_sheet_name(sheet_name, taken_names, index + 1)
79
+ end
80
+
81
+ end
82
+ end
@@ -0,0 +1,62 @@
1
+ module Rubyxls
2
+ class StyleManager
3
+
4
+ def initialize(opts={})
5
+ @styles = {}
6
+ initialize_default_style!
7
+ initialize_base_styles!
8
+ end
9
+
10
+ def retrieve_style_attributes(styles)
11
+ styles = [] if styles.nil?
12
+ styles.each_with_object(@styles[:default].clone) do |style, combined_styles_hash|
13
+ raise("The style :#{style} has not been defined! Please define or create a new type of Style in the styles directory!") if @styles[style].nil?
14
+ combined_styles_hash.merge!(@styles[style])
15
+ end
16
+ end
17
+
18
+ private
19
+
20
+ def initialize_default_style!
21
+ define_style(style: :default, attributes: { alignment: { horizontal: :left, wrap_text: false, vertical: :bottom }, font_name: 'Arial', sz: 10, border: { style: :none, color: "000000" } })
22
+ end
23
+
24
+ def initialize_base_styles!
25
+ define_style(style: :bold, attributes: { b: true })
26
+ define_style(style: :italic, attributes: { i: true })
27
+ define_style(style: :underline, attributes: { u: true })
28
+ define_style(style: :strike, attributes: { strike: true })
29
+
30
+ define_style(style: :indent, attributes: { alignment: { indent: 1 } })
31
+
32
+ define_style(style: :left_align, attributes: { alignment: { horizontal: :left } })
33
+ define_style(style: :right_align, attributes: { alignment: { horizontal: :right } })
34
+ define_style(style: :center_align, attributes: { alignment: { horizontal: :center } })
35
+
36
+ define_style(style: :top_align, attributes: { alignment: { vertical: :top } })
37
+ define_style(style: :bottom_align, attributes: { alignment: { vertical: :bottom } })
38
+ define_style(style: :middle_align, attributes: { alignment: { vertical: :center } })
39
+
40
+ define_style(style: :border_right, attributes: { border_right: { style: :thin } })
41
+ define_style(style: :border_left, attributes: { border_left: { style: :thin } })
42
+ define_style(style: :border_top, attributes: { border_top: { style: :thin } })
43
+ define_style(style: :border_bottom, attributes: { border_bottom: { style: :thin } })
44
+ define_style(style: :border_all, attributes: { border_right: { style: :thin }, border_left: { style: :thin }, border_top: { style: :thin }, border_bottom: { style: :thin } })
45
+
46
+ define_style(style: :number, attributes: { format_code: '#,##0_ ;(#,##0)' })
47
+ define_style(style: :decimal, attributes: { format_code: '#,##0.00_ ;(#,##0.00)' })
48
+ define_style(style: :date, attributes: { format_code: 'MM/D/YY' })
49
+ define_style(style: :time, attributes: { format_code: '[$-409]h:mm AM/PM;@' })
50
+ define_style(style: :currency, attributes: { format_code: '$#,##0;($#,##0)' })
51
+ define_style(style: :currency_precision, attributes: { format_code: '$#,##0.00;($#,##0.00)' })
52
+ define_style(style: :percent, attributes: { format_code: '0.00%;(0.00%)' })
53
+
54
+ define_style(style: :wrap_text, attributes: { alignment: { wrap_text: true } })
55
+ end
56
+
57
+ def define_style(style:, attributes: {})
58
+ @styles[style] = attributes if @styles[style].nil?
59
+ end
60
+
61
+ end
62
+ end
@@ -0,0 +1,3 @@
1
+ module Rubyxls
2
+ VERSION = "1.0.0"
3
+ end
@@ -0,0 +1,58 @@
1
+ module Rubyxls
2
+ class ViewModel
3
+
4
+ attr_reader :data_rows
5
+
6
+ def initialize(**opts)
7
+ @data_rows = []
8
+ @data_rows_count = opts.fetch(:rows_count, nil)
9
+
10
+ build_title_row!
11
+ build_header_row!
12
+ build_data_rows!
13
+ build_additional_rows! unless @data_rows_count.nil?
14
+ build_total_row!
15
+ end
16
+
17
+ private
18
+
19
+ def build_title_row!
20
+ []
21
+ end
22
+
23
+ def build_header_row!
24
+ []
25
+ end
26
+
27
+ def build_data_rows!
28
+ []
29
+ end
30
+
31
+ def build_additional_row!
32
+ []
33
+ end
34
+
35
+ def build_total_row!
36
+ []
37
+ end
38
+
39
+ def build_additional_rows!
40
+ until @data_rows.size == @data_rows_count do
41
+ build_additional_row!
42
+ end
43
+ end
44
+
45
+ def add_empty_cell(*style)
46
+ { value: nil, style: style }
47
+ end
48
+
49
+ def limit_data_to_data_rows_count(data)
50
+ @data_rows_count.nil? ? data : data[0...calculate_data_rows_remaining]
51
+ end
52
+
53
+ def calculate_data_rows_remaining
54
+ @data_rows_count - @data_rows.size
55
+ end
56
+
57
+ end
58
+ end
@@ -0,0 +1,129 @@
1
+ require 'delegate'
2
+
3
+ module Rubyxls
4
+ class Workbook < SimpleDelegator
5
+
6
+ attr_reader :sheets
7
+
8
+ def initialize(**opts)
9
+ @package = Axlsx::Package.new
10
+ @package.use_shared_strings = true
11
+ @name = opts.fetch(:name, "default_workbook")
12
+ @style_codes = {}
13
+ @sheets = []
14
+
15
+ super(@package.workbook)
16
+ build_sheets!
17
+ add_sheets!
18
+ end
19
+
20
+ def to_stream
21
+ @package.to_stream
22
+ end
23
+
24
+ def filename
25
+ "#{@name}.xlsx"
26
+ end
27
+
28
+ private
29
+
30
+ def build_sheets!
31
+ @sheets << Rubyxls::Sheet.new
32
+ end
33
+
34
+ def add_sheets!
35
+ @sheets.each do |sheet|
36
+ @data_validations = {}
37
+ add_sheet(sheet.build_options(*workbook_sheet_names))
38
+ add_rows(sheet.build_rows)
39
+ add_data_validations
40
+ add_charts(sheet.build_charts)
41
+ add_width_normalization(sheet.build_width_normalization)
42
+ end
43
+ end
44
+
45
+ def add_sheet(options)
46
+ add_worksheet(options) do |sheet|
47
+ sheet.sheet_view.show_grid_lines = false
48
+ sheet.page_setup.fit_to(width: 1, height: 999)
49
+ @sheet = sheet
50
+ end
51
+ end
52
+
53
+ def add_rows(rows)
54
+ rows.each do |row|
55
+ values = []
56
+ widths = []
57
+ styles = []
58
+ height = nil
59
+ row.each do |cell|
60
+ values << cell[:value]
61
+ widths << cell[:width]
62
+ styles << retrieve_style_code(cell[:style])
63
+ height = cell[:height] if cell[:height]
64
+ merge_cell(cell) if cell[:merge]
65
+ @data_validations["#{cell[:column]}#{cell[:row]}"] = cell[:data_validation] if cell[:data_validation]
66
+ end
67
+ @sheet.add_row(values, { style: styles, widths: widths, height: height })
68
+ end
69
+ end
70
+
71
+ def retrieve_style_code(style_attributes)
72
+ hash_attributes = style_attributes.clone
73
+ @style_codes[hash_attributes] ||= styles.add_style(style_attributes)
74
+ end
75
+
76
+ def merge_cell(cell)
77
+ case cell[:merge]
78
+ when :right
79
+ @sheet.merge_cells("#{cell[:column]}#{cell[:row]}:#{cell[:column].next}#{cell[:row]}")
80
+ when :down
81
+ @sheet.merge_cells("#{cell[:column]}#{cell[:row]}:#{cell[:column]}#{cell[:row] + 1}")
82
+ end
83
+ end
84
+
85
+ def add_data_validations
86
+ @data_validations.each do |data_validation_cell, data_validation_values|
87
+ start_column = "A"
88
+ end_column = start_column.clone
89
+ (data_validation_values.size - 1).times { end_column.next! }
90
+ @sheet.add_row(data_validation_values, { style: Array.new(data_validation_values.size, retrieve_style_code({ fg_color: "FFFFFF", bg_color: "FFFFFF" })) })
91
+ @sheet.add_data_validation(data_validation_cell, { type: :list, formula1: "$#{start_column}$#{@sheet.rows.count}:$#{end_column}$#{@sheet.rows.count}", showDropdown: false })
92
+ end
93
+ end
94
+
95
+ def add_charts(charts)
96
+ charts.each do |chart|
97
+ @sheet.add_chart(chart.type, start_at: chart.start_at, end_at: chart.end_at, rotX: chart.rot_x, rotY: chart.rot_y) do |added_chart|
98
+ added_chart.title = chart.title
99
+ added_chart.bar_dir = chart.bar_dir if added_chart.respond_to?(:bar_dir)
100
+ added_chart.show_legend = chart.show_legend
101
+ added_chart.catAxis.title = chart.cat_axis_title if added_chart.respond_to?(:catAxis)
102
+ added_chart.valAxis.title = chart.val_axis_title if added_chart.respond_to?(:valAxis)
103
+ added_chart.catAxis.gridlines = chart.cat_axis_gridlines if added_chart.respond_to?(:catAxis)
104
+ added_chart.valAxis.gridlines = chart.val_axis_gridlines if added_chart.respond_to?(:valAxis)
105
+ chart.series.each do |series|
106
+ added_chart.add_series(data: @sheet[series[:data]], labels: @sheet[series[:labels]], colors: series[:colors])
107
+ end
108
+ end
109
+ end
110
+ end
111
+
112
+ def add_width_normalization(custom_widths: [], default_width: nil)
113
+ if @sheet.rows.size > 0
114
+ row_values = Array.new(@sheet.cols.count, nil)
115
+ row_widths = Array.new(@sheet.cols.count, default_width)
116
+ custom_widths.reverse.each do |custom_width|
117
+ row_widths.unshift(custom_width)
118
+ row_widths.pop
119
+ end
120
+ @sheet.add_row(row_values, { widths: row_widths })
121
+ end
122
+ end
123
+
124
+ def workbook_sheet_names
125
+ @package.workbook.worksheets.map(&:name)
126
+ end
127
+
128
+ end
129
+ end
@@ -0,0 +1,29 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'rubyxls/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "rubyxls"
8
+ spec.version = Rubyxls::VERSION
9
+ spec.authors = ["Alexander Frankel"]
10
+ spec.email = ["alexxander.frankel@gmail.com"]
11
+
12
+ spec.summary = %q{A simple DSL for generating XLS files in plain-old ruby.}
13
+ spec.description = %q{Generate XLS files using ruby. Rubyxls provides a simple DSL to
14
+ express anything from simple ruby strings to complex Active Record models.
15
+ Support for multi-sheet workbooks, chart generation, and formula based cells included.}
16
+ spec.homepage = "https://github.com/alexanderfrankel/rubyxls"
17
+ spec.license = "MIT"
18
+
19
+ spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
20
+ spec.bindir = "exe"
21
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
22
+ spec.require_paths = ["lib"]
23
+
24
+ spec.add_development_dependency "bundler"
25
+ spec.add_development_dependency "rake", "~> 10.0"
26
+ spec.add_development_dependency "rspec", "~> 3.0"
27
+
28
+ spec.add_runtime_dependency "axlsx", "~> 2.0.1"
29
+ end
metadata ADDED
@@ -0,0 +1,127 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: rubyxls
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.0
5
+ platform: ruby
6
+ authors:
7
+ - Alexander Frankel
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2016-04-01 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '10.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '10.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rspec
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '3.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '3.0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: axlsx
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: 2.0.1
62
+ type: :runtime
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: 2.0.1
69
+ description: |-
70
+ Generate XLS files using ruby. Rubyxls provides a simple DSL to
71
+ express anything from simple ruby strings to complex Active Record models.
72
+ Support for multi-sheet workbooks, chart generation, and formula based cells included.
73
+ email:
74
+ - alexxander.frankel@gmail.com
75
+ executables: []
76
+ extensions: []
77
+ extra_rdoc_files: []
78
+ files:
79
+ - ".gitignore"
80
+ - ".rspec"
81
+ - CODE_OF_CONDUCT.md
82
+ - Gemfile
83
+ - LICENSE.txt
84
+ - README.md
85
+ - Rakefile
86
+ - bin/console
87
+ - bin/generate_default
88
+ - bin/setup
89
+ - circle.yml
90
+ - lib/rubyxls.rb
91
+ - lib/rubyxls/builders/cell_builder.rb
92
+ - lib/rubyxls/builders/chart_builder.rb
93
+ - lib/rubyxls/builders/formula_builder.rb
94
+ - lib/rubyxls/builders/row_builder.rb
95
+ - lib/rubyxls/report.rb
96
+ - lib/rubyxls/sheet.rb
97
+ - lib/rubyxls/style_manager.rb
98
+ - lib/rubyxls/version.rb
99
+ - lib/rubyxls/view_model.rb
100
+ - lib/rubyxls/workbook.rb
101
+ - rubyxls.gemspec
102
+ homepage: https://github.com/alexanderfrankel/rubyxls
103
+ licenses:
104
+ - MIT
105
+ metadata: {}
106
+ post_install_message:
107
+ rdoc_options: []
108
+ require_paths:
109
+ - lib
110
+ required_ruby_version: !ruby/object:Gem::Requirement
111
+ requirements:
112
+ - - ">="
113
+ - !ruby/object:Gem::Version
114
+ version: '0'
115
+ required_rubygems_version: !ruby/object:Gem::Requirement
116
+ requirements:
117
+ - - ">="
118
+ - !ruby/object:Gem::Version
119
+ version: '0'
120
+ requirements: []
121
+ rubyforge_project:
122
+ rubygems_version: 2.4.5.1
123
+ signing_key:
124
+ specification_version: 4
125
+ summary: A simple DSL for generating XLS files in plain-old ruby.
126
+ test_files: []
127
+ has_rdoc: