diff options
| author | Zsolt Kozaroczy <[email protected]> | 2023-04-12 16:55:10 +0200 |
|---|---|---|
| committer | GitHub <[email protected]> | 2023-04-12 16:55:10 +0200 |
| commit | 4643fbded250a02191f0e652618ee23fcf26c8b6 (patch) | |
| tree | 1b4fa5d8c85ed10c866b22e0cc7c480ffe7921de /lib | |
| parent | bad5cac91b653848bffb4fb45326664f9d806ed2 (diff) | |
| parent | c4bd23bdb6b20763027370f7db13cef1ed7d6e75 (diff) | |
| download | caxlsx-4643fbded250a02191f0e652618ee23fcf26c8b6.tar.gz caxlsx-4643fbded250a02191f0e652618ee23fcf26c8b6.zip | |
Merge pull request #191 from tagliala/chore/add-rubocop
Add RuboCop (and fix simple whitespace, magic comment, trailing comma offenses)
Diffstat (limited to 'lib')
142 files changed, 1025 insertions, 1303 deletions
diff --git a/lib/axlsx.rb b/lib/axlsx.rb index 23082b71..2ee8a1d8 100644 --- a/lib/axlsx.rb +++ b/lib/axlsx.rb @@ -1,4 +1,3 @@ -# encoding: UTF-8 require 'htmlentities' require 'axlsx/version.rb' require 'marcel' @@ -22,11 +21,11 @@ require 'axlsx/rels/relationships.rb' require 'axlsx/drawing/drawing.rb' require 'axlsx/workbook/workbook.rb' require 'axlsx/package.rb' -#required gems +# required gems require 'nokogiri' require 'zip' -#core dependencies +# core dependencies require 'bigdecimal' require 'set' require 'time' @@ -55,7 +54,7 @@ module Axlsx end # determines the cell range for the items provided - def self.cell_range(cells, absolute=true) + def self.cell_range(cells, absolute = true) return "" unless cells.first.is_a? Cell first_cell, last_cell = cells.minmax_by(&:pos) @@ -76,7 +75,7 @@ module Axlsx cells.sort_by(&:pos) end - #global reference html entity encoding + # global reference html entity encoding # @return [HtmlEntities] def self.coder @@coder ||= ::HTMLEntities.new @@ -89,7 +88,7 @@ module Axlsx letters_str = name[/[A-Z]+/] # capitalization?!? - v = letters_str.reverse.chars.reduce({:base=>1, :i=>0}) do |val, c| + v = letters_str.reverse.chars.reduce({ :base => 1, :i => 0 }) do |val, c| val[:i] += ((c.bytes.first - 64) * val[:base]) val[:base] *= 26 @@ -124,7 +123,7 @@ module Axlsx # @example Relative Cell Reference # ws.rows.first.cells.first.r #=> "A1" def self.cell_r(c_index, r_index) - col_ref(c_index) << (r_index+1).to_s + col_ref(c_index) << (r_index + 1).to_s end # Creates an array of individual cell references based on an excel reference range. @@ -144,10 +143,10 @@ module Axlsx # performs the increadible feat of changing snake_case to CamelCase # @param [String] s The snake case string to camelize # @return [String] - def self.camel(s="", all_caps = true) + def self.camel(s = "", all_caps = true) s = s.to_s s = s.capitalize if all_caps - s.gsub(/_(.)/){ $1.upcase } + s.gsub(/_(.)/) { $1.upcase } end # returns the provided string with all invalid control charaters diff --git a/lib/axlsx/content_type/abstract_content_type.rb b/lib/axlsx/content_type/abstract_content_type.rb index 82a659dd..45bd4853 100644 --- a/lib/axlsx/content_type/abstract_content_type.rb +++ b/lib/axlsx/content_type/abstract_content_type.rb @@ -1,14 +1,12 @@ module Axlsx - # This class extracts the common parts from Default and Override class AbstractContentType - include Axlsx::OptionsParser # Initializes an abstract content type # @see Default, Override - def initialize(options={}) - parse_options options + def initialize(options = {}) + parse_options options end # The type of content. @@ -27,6 +25,5 @@ module Axlsx str << Axlsx.instance_values_for(self).map { |key, value| Axlsx::camel(key) << '="' << value.to_s << '"' }.join(' ') str << '/>' end - end end diff --git a/lib/axlsx/content_type/content_type.rb b/lib/axlsx/content_type/content_type.rb index 5d36d685..48b5b6a9 100644 --- a/lib/axlsx/content_type/content_type.rb +++ b/lib/axlsx/content_type/content_type.rb @@ -1,4 +1,3 @@ -# encoding: UTF-8 module Axlsx require 'axlsx/content_type/abstract_content_type.rb' require 'axlsx/content_type/default.rb' @@ -6,7 +5,6 @@ module Axlsx # ContentTypes used in the package. This is automatically managed by the package package. class ContentType < SimpleTypedList - def initialize super [Override, Default] end @@ -20,7 +18,5 @@ module Axlsx each { |type| type.to_xml_string(str) } str << '</Types>' end - end - end diff --git a/lib/axlsx/content_type/default.rb b/lib/axlsx/content_type/default.rb index 3fe15609..d5901456 100644 --- a/lib/axlsx/content_type/default.rb +++ b/lib/axlsx/content_type/default.rb @@ -1,9 +1,6 @@ -# encoding: UTF-8 module Axlsx - # An default content part. These parts are automatically created by for you based on the content of your package. class Default < AbstractContentType - # The serialization node name for this class NODE_NAME = 'Default' @@ -17,9 +14,8 @@ module Axlsx alias :Extension= :extension= # Serializes this object to xml - def to_xml_string(str ='') + def to_xml_string(str = '') super(NODE_NAME, str) end end - end diff --git a/lib/axlsx/content_type/override.rb b/lib/axlsx/content_type/override.rb index 7a8e33fa..5fb98d4c 100644 --- a/lib/axlsx/content_type/override.rb +++ b/lib/axlsx/content_type/override.rb @@ -1,10 +1,6 @@ - -# encoding: UTF-8 module Axlsx - # An override content part. These parts are automatically created by for you based on the content of your package. class Override < AbstractContentType - # Serialization node name for this object NODE_NAME = 'Override' diff --git a/lib/axlsx/doc_props/app.rb b/lib/axlsx/doc_props/app.rb index c7df1fcb..965b34dc 100644 --- a/lib/axlsx/doc_props/app.rb +++ b/lib/axlsx/doc_props/app.rb @@ -1,6 +1,4 @@ -# encoding: UTF-8 module Axlsx - # App represents the app.xml document. The attributes for this object are primarily managed by the application the end user uses to edit the document. None of the attributes are required to serialize a valid xlsx object. # @see shared-documentPropertiesExtended.xsd # @note Support is not implemented for the following complex types: @@ -10,7 +8,6 @@ module Axlsx # HLinks (VectorVariant), # DigSig (DigSigBlob) class App - include Axlsx::OptionsParser # Creates an App object @@ -36,7 +33,7 @@ module Axlsx # @option options [String] application # @option options [String] app_version # @option options [Integer] doc_security - def initialize(options={}) + def initialize(options = {}) parse_options options end @@ -229,7 +226,5 @@ module Axlsx end str << '</Properties>' end - end - end diff --git a/lib/axlsx/doc_props/core.rb b/lib/axlsx/doc_props/core.rb index bb2da676..0f3b6333 100644 --- a/lib/axlsx/doc_props/core.rb +++ b/lib/axlsx/doc_props/core.rb @@ -1,15 +1,12 @@ -# encoding: UTF-8 module Axlsx - # The core object for the package. # @note Packages manage their own core object. # @see Package#core class Core - # Creates a new Core object. # @option options [String] creator # @option options [Time] created - def initialize(options={}) + def initialize(options = {}) @creator = options[:creator] || 'axlsx' @created = options[:created] end @@ -33,7 +30,5 @@ module Axlsx str << '<cp:revision>0</cp:revision>' str << '</cp:coreProperties>' end - end - end diff --git a/lib/axlsx/drawing/area_chart.rb b/lib/axlsx/drawing/area_chart.rb index 2002840c..0c5193c6 100644 --- a/lib/axlsx/drawing/area_chart.rb +++ b/lib/axlsx/drawing/area_chart.rb @@ -1,6 +1,4 @@ -# encoding: UTF-8 module Axlsx - # The AreaChart is a two dimentional line chart (who would have guessed?) that you can add to your worksheet. # @example Creating a chart # # This example creates a line in a single sheet. @@ -20,7 +18,6 @@ module Axlsx # @see Series # @see Package#serialize class AreaChart < Chart - # the category axis # @return [CatAxis] def cat_axis @@ -35,7 +32,7 @@ module Axlsx end alias :valAxis :val_axis - # must be one of [:percentStacked, :clustered, :standard, :stacked] + # must be one of [:percentStacked, :clustered, :standard, :stacked] # @return [Symbol] attr_reader :grouping @@ -45,7 +42,7 @@ module Axlsx # @option options [Boolean] show_legend # @option options [Symbol] grouping # @see Chart - def initialize(frame, options={}) + def initialize(frame, options = {}) @vary_colors = false @grouping = :standard super(frame, options) @@ -66,7 +63,7 @@ module Axlsx def node_name path = self.class.to_s if i = path.rindex('::') - path = path[(i+2)..-1] + path = path[(i + 2)..-1] end path[0] = path[0].chr.downcase path diff --git a/lib/axlsx/drawing/area_series.rb b/lib/axlsx/drawing/area_series.rb index c039869e..7995c5bc 100644 --- a/lib/axlsx/drawing/area_series.rb +++ b/lib/axlsx/drawing/area_series.rb @@ -1,11 +1,9 @@ -# encoding: UTF-8 module Axlsx # A AreaSeries defines the title, data and labels for line charts # @note The recommended way to manage series is to use Chart#add_series # @see Worksheet#add_chart # @see Chart#add_series class AreaSeries < Series - # The data for this series. # @return [ValAxisData] attr_reader :data @@ -35,7 +33,7 @@ module Axlsx # @option options [Array, SimpleTypedList] data # @option options [Array, SimpleTypedList] labels # @param [Chart] chart - def initialize(chart, options={}) + def initialize(chart, options = {}) @show_marker = false @marker_symbol = options[:marker_symbol] ? options[:marker_symbol] : :default @smooth = false @@ -105,6 +103,5 @@ module Axlsx # assigns the labels for this series def labels=(v) DataTypeValidator.validate "Series.labels", [AxDataSource], v; @labels = v; end - end end diff --git a/lib/axlsx/drawing/ax_data_source.rb b/lib/axlsx/drawing/ax_data_source.rb index ebbfe2cd..b8aafc5e 100644 --- a/lib/axlsx/drawing/ax_data_source.rb +++ b/lib/axlsx/drawing/ax_data_source.rb @@ -1,13 +1,11 @@ module Axlsx - # An axis data source that can contain referenced or literal strings or numbers # @note only string data types are supported - mainly because we have not implemented a chart type that requires a numerical axis value class AxDataSource < NumDataSource - # creates a new NumDataSource object # @option options [Array] data An array of Cells or Numeric objects # @option options [Symbol] tag_name see tag_name - def initialize(options={}) + def initialize(options = {}) @tag_name = :cat @data_type = StrData @ref_tag_name = :strRef @@ -19,8 +17,5 @@ module Axlsx def self.allowed_tag_names [:xVal, :cat] end - end - end - diff --git a/lib/axlsx/drawing/axes.rb b/lib/axlsx/drawing/axes.rb index dff87a9b..314f28c3 100644 --- a/lib/axlsx/drawing/axes.rb +++ b/lib/axlsx/drawing/axes.rb @@ -1,22 +1,21 @@ module Axlsx - # The Axes class creates and manages axis information and # serialization for charts. class Axes - # @param [Hash] options options used to generate axis each key # should be an axis name like :val_axis and its value should be the # class of the axis type to construct. The :cat_axis, if there is one, # must come first (we assume a Ruby 1.9+ Hash or an OrderedHash). - def initialize(options={}) + def initialize(options = {}) raise(ArgumentError, "CatAxis must come first") if options.keys.include?(:cat_axis) && options.keys.first != :cat_axis + options.each do |name, axis_class| add_axis(name, axis_class) end end # [] provides assiciative access to a specic axis store in an axes - # instance. + # instance. # @return [Axis] def [](name) axes.assoc(name)[1] @@ -27,12 +26,12 @@ module Axlsx # @param [Hash] options # @option options ids # If the ids option is specified only the axis identifier is - # serialized. Otherwise, each axis is serialized in full. + # serialized. Otherwise, each axis is serialized in full. def to_xml_string(str = '', options = {}) if options[:ids] # CatAxis must come first in the XML (for Microsoft Excel at least) sorted = axes.sort_by { |name, axis| axis.kind_of?(CatAxis) ? 0 : 1 } - sorted.each { |axis| str << ('<c:axId val="' << axis[1].id.to_s << '"/>') } + sorted.each { |axis| str << ('<c:axId val="' << axis[1].id.to_s << '"/>') } else axes.each { |axis| axis[1].to_xml_string(str) } end diff --git a/lib/axlsx/drawing/axis.rb b/lib/axlsx/drawing/axis.rb index b2bb8fe7..9ca03fb1 100644 --- a/lib/axlsx/drawing/axis.rb +++ b/lib/axlsx/drawing/axis.rb @@ -1,9 +1,6 @@ -# encoding: UTF-8 module Axlsx - # the access class defines common properties and values for a chart axis. class Axis - include Axlsx::OptionsParser # Creates an Axis object @@ -12,11 +9,11 @@ module Axlsx # @option options [Symbol] crosses # @option options [Symbol] tick_lbl_pos # @raise [ArgumentError] If axi_id or cross_ax are not unsigned integers - def initialize(options={}) - @id = rand(8 ** 8) + def initialize(options = {}) + @id = rand(8**8) @format_code = "General" @delete = @label_rotation = 0 - @scaling = Scaling.new(:orientation=>:minMax) + @scaling = Scaling.new(:orientation => :minMax) @title = @color = nil self.ax_pos = :b self.tick_lbl_pos = :nextTo @@ -83,19 +80,19 @@ module Axlsx # the title for the axis. This can be a cell or a fixed string. attr_reader :title - # The color for this axis. This value is used when rendering the axis line in the chart. + # The color for this axis. This value is used when rendering the axis line in the chart. # colors should be in 6 character rbg format # @return [String] the rbg color assinged. # @see color def color=(color_rgb) @color = color_rgb end - + # The crossing axis for this axis # @param [Axis] axis def cross_axis=(axis) - DataTypeValidator.validate "#{self.class}.cross_axis", [Axis], axis - @cross_axis = axis + DataTypeValidator.validate "#{self.class}.cross_axis", [Axis], axis + @cross_axis = axis end # The position of the axis @@ -184,7 +181,5 @@ module Axlsx str << ('<c:crossAx val="' << @cross_axis.id.to_s << '"/>') str << ('<c:crosses val="' << @crosses.to_s << '"/>') end - end - end diff --git a/lib/axlsx/drawing/bar_3D_chart.rb b/lib/axlsx/drawing/bar_3D_chart.rb index ae6c2007..89544be0 100644 --- a/lib/axlsx/drawing/bar_3D_chart.rb +++ b/lib/axlsx/drawing/bar_3D_chart.rb @@ -1,13 +1,10 @@ -# encoding: UTF-8 module Axlsx - # The Bar3DChart is a three dimentional barchart (who would have guessed?) that you can add to your worksheet. # @see Worksheet#add_chart # @see Chart#add_series # @see Package#serialize # @see README for an example class Bar3DChart < Chart - # the category axis # @return [CatAxis] def cat_axis @@ -42,7 +39,7 @@ module Axlsx end alias :gapWidth :gap_width - #grouping for a column, line, or area chart. + # grouping for a column, line, or area chart. # must be one of [:percentStacked, :clustered, :standard, :stacked] # @return [Symbol] def grouping @@ -73,12 +70,12 @@ module Axlsx # @option options [Integer] perspective # @see Chart # @see View3D - def initialize(frame, options={}) + def initialize(frame, options = {}) @vary_colors = true @gap_width, @gap_depth, @shape = nil, nil, nil super(frame, options) @series_type = BarSeries - @view_3D = View3D.new({:r_ang_ax=>1}.merge(options)) + @view_3D = View3D.new({ :r_ang_ax => 1 }.merge(options)) @d_lbls = nil end @@ -90,7 +87,7 @@ module Axlsx end alias :barDir= :bar_dir= - #grouping for a column, line, or area chart. + # grouping for a column, line, or area chart. # must be one of [:percentStacked, :clustered, :standard, :stacked] def grouping=(v) RestrictionValidator.validate "Bar3DChart.grouping", [:percentStacked, :clustered, :standard, :stacked], v @@ -100,14 +97,14 @@ module Axlsx # space between bar or column clusters, as a percentage of the bar or column width. def gap_width=(v) RangeValidator.validate "Bar3DChart.gap_width", 0, 500, v - @gap_width=(v) + @gap_width = (v) end alias :gapWidth= :gap_width= # space between bar or column clusters, as a percentage of the bar or column width. def gap_depth=(v) RangeValidator.validate "Bar3DChart.gap_depth", 0, 500, v - @gap_depth=(v) + @gap_depth = (v) end alias :gapDepth= :gap_depth= @@ -142,7 +139,7 @@ module Axlsx # category axes specified via axes[:val_axes] and axes[:cat_axis] # @return [Axes] def axes - @axes ||= Axes.new(:cat_axis => CatAxis, :val_axis => ValAxis) + @axes ||= Axes.new(:cat_axis => CatAxis, :val_axis => ValAxis) end end end diff --git a/lib/axlsx/drawing/bar_chart.rb b/lib/axlsx/drawing/bar_chart.rb index 67787361..1ed38332 100644 --- a/lib/axlsx/drawing/bar_chart.rb +++ b/lib/axlsx/drawing/bar_chart.rb @@ -1,13 +1,10 @@ -# encoding: UTF-8 module Axlsx - # The BarChart is a two dimentional barchart that you can add to your worksheet. # @see Worksheet#add_chart # @see Chart#add_series # @see Package#serialize # @see README for an example class BarChart < Chart - # the category axis # @return [CatAxis] def cat_axis @@ -37,7 +34,7 @@ module Axlsx end alias :gapWidth :gap_width - #grouping for a column, line, or area chart. + # grouping for a column, line, or area chart. # must be one of [:percentStacked, :clustered, :standard, :stacked] # @return [Symbol] def grouping @@ -66,7 +63,7 @@ module Axlsx # @option options [String] gap_width # @option options [Symbol] shape # @see Chart - def initialize(frame, options={}) + def initialize(frame, options = {}) @vary_colors = true @gap_width, @overlap, @shape = nil, nil, nil super(frame, options) @@ -82,7 +79,7 @@ module Axlsx end alias :barDir= :bar_dir= - #grouping for a column, line, or area chart. + # grouping for a column, line, or area chart. # must be one of [:percentStacked, :clustered, :standard, :stacked] def grouping=(v) RestrictionValidator.validate "BarChart.grouping", [:percentStacked, :clustered, :standard, :stacked], v @@ -92,13 +89,13 @@ module Axlsx # space between bar or column clusters, as a percentage of the bar or column width. def gap_width=(v) RangeValidator.validate "BarChart.gap_width", 0, 500, v - @gap_width=(v) + @gap_width = (v) end alias :gapWidth= :gap_width= def overlap=(v) RangeValidator.validate "BarChart.overlap", -100, 100, v - @overlap=(v) + @overlap = (v) end # The shape of the bars or columns @@ -132,7 +129,7 @@ module Axlsx # category axes specified via axes[:val_axes] and axes[:cat_axis] # @return [Axes] def axes - @axes ||= Axes.new(:cat_axis => CatAxis, :val_axis => ValAxis) + @axes ||= Axes.new(:cat_axis => CatAxis, :val_axis => ValAxis) end end end diff --git a/lib/axlsx/drawing/bar_series.rb b/lib/axlsx/drawing/bar_series.rb index 0e5d1168..0b4d9614 100644 --- a/lib/axlsx/drawing/bar_series.rb +++ b/lib/axlsx/drawing/bar_series.rb @@ -1,12 +1,9 @@ -# encoding: UTF-8 module Axlsx # A BarSeries defines the title, data and labels for bar charts # @note The recommended way to manage series is to use Chart#add_series # @see Worksheet#add_chart # @see Chart#add_series class BarSeries < Series - - # The data for this series. # @return [NumDataSource] attr_reader :data @@ -35,11 +32,11 @@ module Axlsx # @option options [String] colors an array of colors to use when rendering each data point # @option options [String] series_color a color to use when rendering series # @param [Chart] chart - def initialize(chart, options={}) + def initialize(chart, options = {}) @shape = :box @colors = [] super(chart, options) - self.labels = AxDataSource.new({:data => options[:labels]}) unless options[:labels].nil? + self.labels = AxDataSource.new({ :data => options[:labels] }) unless options[:labels].nil? self.data = NumDataSource.new(options) unless options[:data].nil? end @@ -61,7 +58,6 @@ module Axlsx # @return [String] def to_xml_string(str = '') super(str) do - colors.each_with_index do |c, index| str << '<c:dPt>' str << ('<c:idx val="' << index.to_s << '"/>') @@ -91,7 +87,5 @@ module Axlsx # assigns the labels for this series def labels=(v) DataTypeValidator.validate "Series.labels", [AxDataSource], v; @labels = v; end - end - end diff --git a/lib/axlsx/drawing/bubble_chart.rb b/lib/axlsx/drawing/bubble_chart.rb index e08e6f7c..084d0477 100644 --- a/lib/axlsx/drawing/bubble_chart.rb +++ b/lib/axlsx/drawing/bubble_chart.rb @@ -1,12 +1,9 @@ -# encoding: UTF-8 module Axlsx - # The BubbleChart allows you to insert a bubble chart into your worksheet # @see Worksheet#add_chart # @see Chart#add_series # @see README for an example class BubbleChart < Chart - include Axlsx::OptionsParser # the x value axis @@ -24,10 +21,10 @@ module Axlsx alias :yValAxis :y_val_axis # Creates a new bubble chart - def initialize(frame, options={}) + def initialize(frame, options = {}) @vary_colors = 0 - super(frame, options) + super(frame, options) @series_type = BubbleSeries @d_lbls = nil parse_options options diff --git a/lib/axlsx/drawing/bubble_series.rb b/lib/axlsx/drawing/bubble_series.rb index 07b7be61..78b44bf1 100644 --- a/lib/axlsx/drawing/bubble_series.rb +++ b/lib/axlsx/drawing/bubble_series.rb @@ -1,13 +1,10 @@ -# encoding: UTF-8 module Axlsx - # A BubbleSeries defines the x/y position and bubble size of data in the chart # @note The recommended way to manage series is to use Chart#add_series # @see Worksheet#add_chart # @see Chart#add_series # @see examples/example.rb class BubbleSeries < Series - # The x data for this series. # @return [AxDataSource] attr_reader :xData @@ -26,12 +23,12 @@ module Axlsx attr_reader :color # Creates a new BubbleSeries - def initialize(chart, options={}) + def initialize(chart, options = {}) @xData, @yData, @bubbleSize = nil super(chart, options) @xData = AxDataSource.new(:tag_name => :xVal, :data => options[:xData]) unless options[:xData].nil? - @yData = NumDataSource.new({:tag_name => :yVal, :data => options[:yData]}) unless options[:yData].nil? - @bubbleSize = NumDataSource.new({:tag_name => :bubbleSize, :data => options[:bubbleSize]}) unless options[:bubbleSize].nil? + @yData = NumDataSource.new({ :tag_name => :yVal, :data => options[:yData] }) unless options[:yData].nil? + @bubbleSize = NumDataSource.new({ :tag_name => :bubbleSize, :data => options[:bubbleSize] }) unless options[:bubbleSize].nil? end # @see color diff --git a/lib/axlsx/drawing/cat_axis.rb b/lib/axlsx/drawing/cat_axis.rb index 6091b972..75290da0 100644 --- a/lib/axlsx/drawing/cat_axis.rb +++ b/lib/axlsx/drawing/cat_axis.rb @@ -1,12 +1,10 @@ -# encoding: UTF-8 module Axlsx - #A CatAxis object defines a chart category axis + # A CatAxis object defines a chart category axis class CatAxis < Axis - # Creates a new CatAxis object # @option options [Integer] tick_lbl_skip # @option options [Integer] tick_mark_skip - def initialize(options={}) + def initialize(options = {}) @tick_lbl_skip = 1 @tick_mark_skip = 1 self.auto = 1 @@ -78,8 +76,5 @@ module Axlsx str << ('<c:tickMarkSkip val="' << @tick_mark_skip.to_s << '"/>') str << '</c:catAx>' end - end - - end diff --git a/lib/axlsx/drawing/chart.rb b/lib/axlsx/drawing/chart.rb index 500353cf..e9f4441f 100644 --- a/lib/axlsx/drawing/chart.rb +++ b/lib/axlsx/drawing/chart.rb @@ -1,11 +1,8 @@ -# encoding: UTF-8 module Axlsx - # A Chart is the superclass for specific charts # @note Worksheet#add_chart is the recommended way to create charts for your worksheets. # @see README for examples class Chart - include Axlsx::OptionsParser # Creates a new chart object # @param [GraphicalFrame] frame The frame that holds this chart. @@ -16,10 +13,10 @@ module Axlsx # @option options [Array|String|Cell] end_at The X, Y coordinates defining the bottom right corner of the chart. # @option options [Boolean] plot_visible_only (true) Whether only data from visible cells should be plotted. # @option options [Boolean] rounded_corners (true) Whether the chart area shall have rounded corners. - def initialize(frame, options={}) + def initialize(frame, options = {}) @style = 18 @view_3D = nil - @graphic_frame=frame + @graphic_frame = frame @graphic_frame.anchor.drawing.worksheet.workbook.charts << self @series = SimpleTypedList.new Series @show_legend = true @@ -52,7 +49,7 @@ module Axlsx # @return [Series] attr_reader :series_type - #TODO data labels! + # TODO data labels! def d_lbls @d_lbls ||= DLbls.new(self.class) end @@ -125,7 +122,7 @@ module Axlsx # The part name for this chart # @return [String] def pn - "#{CHART_PN % (index+1)}" + "#{CHART_PN % (index + 1)}" end # The title object for the chart. @@ -181,7 +178,7 @@ module Axlsx # Adds a new series to the chart's series collection. # @return [Series] # @see Series - def add_series(options={}) + def add_series(options = {}) @series_type.new(self, options) @series.last end @@ -275,7 +272,7 @@ module Axlsx # reference or cell to use in setting the start marker position. # @param [Integer] y The row # @return [Marker] - def start_at(x=0, y=0) + def start_at(x = 0, y = 0) @graphic_frame.anchor.start_at(x, y) end @@ -286,14 +283,12 @@ module Axlsx # @param [Integer] y The row - default 10 # @return [Marker] # @see start_at - def end_at(x=10, y=10) + def end_at(x = 10, y = 10) @graphic_frame.anchor.end_at(x, y) end # sets the view_3D object for the chart def view_3D=(v) DataTypeValidator.validate "#{self.class}.view_3D", View3D, v; @view_3D = v; end alias :view3D= :view_3D= - end - end diff --git a/lib/axlsx/drawing/d_lbls.rb b/lib/axlsx/drawing/d_lbls.rb index 0fb3c6ad..358378c5 100644 --- a/lib/axlsx/drawing/d_lbls.rb +++ b/lib/axlsx/drawing/d_lbls.rb @@ -2,15 +2,15 @@ module Axlsx # There are more elements in the dLbls spec that allow for # customizations and formatting. For now, I am just implementing the # basics. - #The DLbls class manages serialization of data labels + # The DLbls class manages serialization of data labels # showLeaderLines and leaderLines are not currently implemented class DLbls - include Axlsx::Accessors - include Axlsx::OptionsParser + include Axlsx::OptionsParser # creates a new DLbls object - def initialize(chart_type, options={}) + def initialize(chart_type, options = {}) raise ArgumentError, 'chart_type must inherit from Chart' unless [Chart, LineChart].include?(chart_type.superclass) + @chart_type = chart_type initialize_defaults parse_options options @@ -18,31 +18,31 @@ module Axlsx # These attributes are all boolean so I'm doing a bit of a hand # waving magic show to set up the attriubte accessors - # @note - # not all charts support all methods! + # @note + # not all charts support all methods! # Bar3DChart and Line3DChart and ScatterChart do not support d_lbl_pos or show_leader_lines - # - boolean_attr_accessor :show_legend_key, - :show_val, - :show_cat_name, - :show_ser_name, - :show_percent, - :show_bubble_size, + # + boolean_attr_accessor :show_legend_key, + :show_val, + :show_cat_name, + :show_ser_name, + :show_percent, + :show_bubble_size, :show_leader_lines # Initialize all the values to false as Excel requires them to # explicitly be disabled or all will show. def initialize_defaults - [:show_legend_key, :show_val, :show_cat_name, - :show_ser_name, :show_percent, :show_bubble_size, + [:show_legend_key, :show_val, :show_cat_name, + :show_ser_name, :show_percent, :show_bubble_size, :show_leader_lines].each do |attr| self.send("#{attr}=", false) end end - # The chart type that is using this data lables instance. + # The chart type that is using this data lables instance. # This affects the xml output as not all chart types support the - # same data label attributes. + # same data label attributes. attr_reader :chart_type # The position of the data labels in the chart @@ -50,6 +50,7 @@ module Axlsx # @return [Symbol] def d_lbl_pos return unless [Pie3DChart, LineChart].include? @chart_type + @d_lbl_pos ||= :bestFit end @@ -61,11 +62,11 @@ module Axlsx # @param [Symbol] label_position the postion you want to use. def d_lbl_pos=(label_position) return unless [Pie3DChart, LineChart].include? @chart_type - Axlsx::RestrictionValidator.validate 'DLbls#d_lbl_pos', [:bestFit, :b, :ctr, :inBase, :inEnd, :l, :outEnd, :r, :t], label_position + + Axlsx::RestrictionValidator.validate 'DLbls#d_lbl_pos', [:bestFit, :b, :ctr, :inBase, :inEnd, :l, :outEnd, :r, :t], label_position @d_lbl_pos = label_position end - # serializes the data labels # @return [String] def to_xml_string(str = '') @@ -74,7 +75,8 @@ module Axlsx instance_vals = Axlsx.instance_values_for(self) %w(d_lbl_pos show_legend_key show_val show_cat_name show_ser_name show_percent show_bubble_size show_leader_lines).each do |key| next unless instance_vals.keys.include?(key) && instance_vals[key] != nil - str << "<c:#{Axlsx::camel(key, false)} val='#{instance_vals[key]}' />" + + str << "<c:#{Axlsx::camel(key, false)} val='#{instance_vals[key]}' />" end str << '</c:dLbls>' end @@ -82,10 +84,9 @@ module Axlsx # nills out d_lbl_pos and show_leader_lines as these attributes, while valid in the spec actually chrash excel for any chart type other than pie charts. def validate_attributes_for_chart_type return if [Pie3DChart, LineChart].include? @chart_type + @d_lbl_pos = nil @show_leader_lines = nil end - - end end diff --git a/lib/axlsx/drawing/drawing.rb b/lib/axlsx/drawing/drawing.rb index e9da37a5..bc6dd1cf 100644 --- a/lib/axlsx/drawing/drawing.rb +++ b/lib/axlsx/drawing/drawing.rb @@ -1,4 +1,3 @@ -# encoding: UTF-8 module Axlsx require 'axlsx/drawing/d_lbls.rb' require 'axlsx/drawing/title.rb' @@ -58,7 +57,6 @@ module Axlsx # @see Chart # see examples/example.rb for an example of how to create a chart. class Drawing - # The worksheet that owns the drawing # @return [Worksheet] attr_reader :worksheet @@ -77,12 +75,11 @@ module Axlsx @anchors = SimpleTypedList.new [TwoCellAnchor, OneCellAnchor] end - # Adds an image to the chart If th end_at option is specified we create a two cell anchor. By default we use a one cell anchor. # @note The recommended way to manage images is to use Worksheet.add_image. Please refer to that method for documentation. # @see Worksheet#add_image # @return [Pic] - def add_image(options={}) + def add_image(options = {}) if options[:end_at] TwoCellAnchor.new(self, options).add_pic(options) else @@ -94,7 +91,7 @@ module Axlsx # Adds a chart to the drawing. # @note The recommended way to manage charts is to use Worksheet.add_chart. Please refer to that method for documentation. # @see Worksheet#add_chart - def add_chart(chart_type, options={}) + def add_chart(chart_type, options = {}) TwoCellAnchor.new(self, options) @anchors.last.add_chart(chart_type, options) end @@ -129,14 +126,14 @@ module Axlsx # The part name for this drawing # @return [String] def pn - "#{DRAWING_PN % (index+1)}" + "#{DRAWING_PN % (index + 1)}" end # The relational part name for this drawing # #NOTE This should be rewritten to return an Axlsx::Relationship object. # @return [String] def rels_pn - "#{DRAWING_RELS_PN % (index+1)}" + "#{DRAWING_RELS_PN % (index + 1)}" end # A list of objects this drawing holds. @@ -162,6 +159,5 @@ module Axlsx anchors.each { |anchor| anchor.to_xml_string(str) } str << '</xdr:wsDr>' end - end end diff --git a/lib/axlsx/drawing/graphic_frame.rb b/lib/axlsx/drawing/graphic_frame.rb index d44415b9..006b3b0f 100644 --- a/lib/axlsx/drawing/graphic_frame.rb +++ b/lib/axlsx/drawing/graphic_frame.rb @@ -1,10 +1,8 @@ -# encoding: UTF-8 module Axlsx # A graphic frame defines a container for a chart object # @note The recommended way to manage charts is Worksheet#add_chart # @see Worksheet#add_chart class GraphicFrame - # A reference to the chart object associated with this frame # @return [Chart] attr_reader :chart @@ -49,6 +47,5 @@ module Axlsx str << '</a:graphic>' str << '</xdr:graphicFrame>' end - end end diff --git a/lib/axlsx/drawing/hyperlink.rb b/lib/axlsx/drawing/hyperlink.rb index fcabd25b..4d3b343d 100644 --- a/lib/axlsx/drawing/hyperlink.rb +++ b/lib/axlsx/drawing/hyperlink.rb @@ -1,14 +1,12 @@ -# encoding: UTF-8 module Axlsx # a hyperlink object adds an action to an image when clicked so that when the image is clicked the link is fecthed. # @note using the hyperlink option when calling add_image on a drawing object is the recommended way to manage hyperlinks # @see {file:README} README class Hyperlink - include Axlsx::SerializedAttributes include Axlsx::OptionsParser - #Creates a hyperlink object + # Creates a hyperlink object # parent must be a Pic for now, although I expect that other object support this tag and its cNvPr parent # @param [Pic] parent # @option options [String] tooltip message shown when hyperlinked object is hovered over with mouse. @@ -19,7 +17,7 @@ module Axlsx # @option options [Boolean] endSnd terminate any sound events when processing this link # @option options [Boolean] history include this link in the list of visited links for the applications history. # @option options [Boolean] highlightClick indicate that the link has already been visited. - def initialize(parent, options={}) + def initialize(parent, options = {}) DataTypeValidator.validate "Hyperlink.parent", [Pic], parent @parent = parent parse_options options @@ -40,7 +38,7 @@ module Axlsx alias :invalidUrl :invalid_url alias :invalidUrl= :invalid_url= - #An action to take when the link is clicked. The specification says "This can be used to specify a slide to be navigated to or a script of code to be run." but in most cases you will not need to do anything with this. MS does reserve a few interesting strings. @see http://msdn.microsoft.com/en-us/library/ff532419%28v=office.12%29.aspx + # An action to take when the link is clicked. The specification says "This can be used to specify a slide to be navigated to or a script of code to be run." but in most cases you will not need to do anything with this. MS does reserve a few interesting strings. @see http://msdn.microsoft.com/en-us/library/ff532419%28v=office.12%29.aspx # @return [String] attr_accessor :action @@ -93,8 +91,7 @@ module Axlsx # @param [String] str # @return [String] def to_xml_string(str = '') - serialized_tag 'a:hlinkClick', str, {:'r:id' => relationship.Id, :'xmlns:r' => XML_NS_R } + serialized_tag 'a:hlinkClick', str, { :'r:id' => relationship.Id, :'xmlns:r' => XML_NS_R } end - end end diff --git a/lib/axlsx/drawing/line_3D_chart.rb b/lib/axlsx/drawing/line_3D_chart.rb index 4132655e..85d04b06 100644 --- a/lib/axlsx/drawing/line_3D_chart.rb +++ b/lib/axlsx/drawing/line_3D_chart.rb @@ -1,6 +1,4 @@ -# encoding: UTF-8 module Axlsx - # The Line3DChart is a three dimentional line chart (who would have guessed?) that you can add to your worksheet. # @example Creating a chart # # This example creates a line in a single sheet. @@ -20,7 +18,6 @@ module Axlsx # @see Series # @see Package#serialize class Line3DChart < Axlsx::LineChart - # space between bar or column clusters, as a percentage of the bar or column width. # @return [String] attr_reader :gap_depth @@ -41,28 +38,27 @@ module Axlsx # @see Chart # @see lineChart # @see View3D - def initialize(frame, options={}) + def initialize(frame, options = {}) @gap_depth = nil - @view_3D = View3D.new({:r_ang_ax=>1}.merge(options)) + @view_3D = View3D.new({ :r_ang_ax => 1 }.merge(options)) super(frame, options) axes.add_axis :ser_axis, SerAxis end - # @see gapDepth def gap_depth=(v) RegexValidator.validate "Line3DChart.gapWidth", GAP_AMOUNT_PERCENT, v - @gap_depth=(v) + @gap_depth = (v) end alias :gapDepth= :gap_depth= - # Serializes the object - # @param [String] str - # @return [String] - def to_xml_string(str = '') - super(str) do - str << ('<c:gapDepth val="' << @gap_depth.to_s << '"/>') unless @gap_depth.nil? - end + # Serializes the object + # @param [String] str + # @return [String] + def to_xml_string(str = '') + super(str) do + str << ('<c:gapDepth val="' << @gap_depth.to_s << '"/>') unless @gap_depth.nil? end + end end end diff --git a/lib/axlsx/drawing/line_chart.rb b/lib/axlsx/drawing/line_chart.rb index a86355d5..1ff2bde5 100644 --- a/lib/axlsx/drawing/line_chart.rb +++ b/lib/axlsx/drawing/line_chart.rb @@ -1,6 +1,4 @@ -# encoding: UTF-8 module Axlsx - # The LineChart is a two dimentional line chart (who would have guessed?) that you can add to your worksheet. # @example Creating a chart # # This example creates a line in a single sheet. @@ -20,7 +18,6 @@ module Axlsx # @see Series # @see Package#serialize class LineChart < Chart - # the category axis # @return [CatAxis] def cat_axis @@ -35,7 +32,7 @@ module Axlsx end alias :valAxis :val_axis - # must be one of [:percentStacked, :clustered, :standard, :stacked] + # must be one of [:percentStacked, :clustered, :standard, :stacked] # @return [Symbol] attr_reader :grouping @@ -45,7 +42,7 @@ module Axlsx # @option options [Boolean] show_legend # @option options [Symbol] grouping # @see Chart - def initialize(frame, options={}) + def initialize(frame, options = {}) @vary_colors = false @grouping = :standard super(frame, options) @@ -66,7 +63,7 @@ module Axlsx def node_name path = self.class.to_s if i = path.rindex('::') - path = path[(i+2)..-1] + path = path[(i + 2)..-1] end path[0] = path[0].chr.downcase path diff --git a/lib/axlsx/drawing/line_series.rb b/lib/axlsx/drawing/line_series.rb index 666e67c8..18719277 100644 --- a/lib/axlsx/drawing/line_series.rb +++ b/lib/axlsx/drawing/line_series.rb @@ -1,11 +1,9 @@ -# encoding: UTF-8 module Axlsx # A LineSeries defines the title, data and labels for line charts # @note The recommended way to manage series is to use Chart#add_series # @see Worksheet#add_chart # @see Chart#add_series class LineSeries < Series - # The data for this series. # @return [ValAxisData] attr_reader :data @@ -35,7 +33,7 @@ module Axlsx # @option options [Array, SimpleTypedList] data # @option options [Array, SimpleTypedList] labels # @param [Chart] chart - def initialize(chart, options={}) + def initialize(chart, options = {}) @show_marker = false @marker_symbol = options[:marker_symbol] ? options[:marker_symbol] : :default @smooth = false @@ -105,6 +103,5 @@ module Axlsx # assigns the labels for this series def labels=(v) DataTypeValidator.validate "Series.labels", [AxDataSource], v; @labels = v; end - end end diff --git a/lib/axlsx/drawing/marker.rb b/lib/axlsx/drawing/marker.rb index 75876fa3..a4933c33 100644 --- a/lib/axlsx/drawing/marker.rb +++ b/lib/axlsx/drawing/marker.rb @@ -1,10 +1,8 @@ -# encoding: UTF-8 module Axlsx # The Marker class defines a point in the worksheet that drawing anchors attach to. # @note The recommended way to manage markers is Worksheet#add_chart Markers are created for a two cell anchor based on the :start and :end options. # @see Worksheet#add_chart class Marker - include Axlsx::OptionsParser # Creates a new Marker object @@ -12,7 +10,7 @@ module Axlsx # @option options [Integer] colOff # @option options [Integer] row # @option options [Integer] rowOff - def initialize(options={}) + def initialize(options = {}) @col, @colOff, @row, @rowOff = 0, 0, 0, 0 parse_options options end @@ -33,7 +31,7 @@ module Axlsx # @return [Integer] attr_reader :rowOff - # @see col + # @see col def col=(v) Axlsx::validate_unsigned_int v; @col = v end # @see colOff def colOff=(v) Axlsx::validate_int v; @colOff = v end @@ -47,7 +45,7 @@ module Axlsx # or an Array. # @param row the row of the marker. This is ignored if the col parameter is a Cell or # String or Array. - def coord(col, row=0) + def coord(col, row = 0) coordinates = parse_coord_args(col, row) self.col = coordinates[0] self.row = coordinates[1] @@ -61,11 +59,12 @@ module Axlsx str << ('<xdr:' << k.to_s << '>' << self.send(k).to_s << '</xdr:' << k.to_s << '>') end end + private # handles multiple inputs for setting the position of a marker # @see Chart#start_at - def parse_coord_args(x, y=0) + def parse_coord_args(x, y = 0) if x.is_a?(String) x, y = *Axlsx::name_to_indices(x) end @@ -77,8 +76,5 @@ module Axlsx end [x, y] end - - end - end diff --git a/lib/axlsx/drawing/num_data.rb b/lib/axlsx/drawing/num_data.rb index 9b7a2587..7239ac5f 100644 --- a/lib/axlsx/drawing/num_data.rb +++ b/lib/axlsx/drawing/num_data.rb @@ -1,16 +1,13 @@ -# -*- coding: utf-8 -*- module Axlsx - - #This class specifies data for a particular data point. It is used for both numCache and numLit object + # This class specifies data for a particular data point. It is used for both numCache and numLit object class NumData - include Axlsx::OptionsParser # creates a new NumVal object # @option options [String] formatCode # @option options [Array] :data # @see StrData - def initialize(options={}) + def initialize(options = {}) @format_code = "General" @pt = SimpleTypedList.new NumVal parse_options options @@ -22,7 +19,7 @@ module Axlsx # Creates the val objects for this data set. I am not overly confident this is going to play nicely with time and data types. # @param [Array] values An array of cells or values. - def data=(values=[]) + def data=(values = []) @tag_name = values.first.is_a?(Cell) ? :numCache : :numLit values.each do |value| value = value.is_formula? ? 0 : value.value if value.is_a?(Cell) @@ -31,7 +28,7 @@ module Axlsx end # @see format_code - def format_code=(v='General') + def format_code=(v = 'General') Axlsx::validate_string(v) @format_code = v end @@ -46,7 +43,5 @@ module Axlsx end str << ('</c:' << @tag_name.to_s << '>') end - end - end diff --git a/lib/axlsx/drawing/num_data_source.rb b/lib/axlsx/drawing/num_data_source.rb index e0e97e41..46f6ba71 100644 --- a/lib/axlsx/drawing/num_data_source.rb +++ b/lib/axlsx/drawing/num_data_source.rb @@ -1,14 +1,12 @@ module Axlsx - # A numeric data source for use by charts. class NumDataSource - include Axlsx::OptionsParser # creates a new NumDataSource object # @option options [Array] data An array of Cells or Numeric objects # @option options [Symbol] tag_name see tag_name - def initialize(options={}) + def initialize(options = {}) # override these three in child classes @data_type ||= NumData @tag_name ||= :val @@ -22,7 +20,6 @@ module Axlsx parse_options options end - # The tag name to use when serializing this data source. # Only items defined in allowed_tag_names are allowed # @return [Symbol] @@ -36,7 +33,7 @@ module Axlsx [:yVal, :val, :bubbleSize] end - # sets the tag name for this data source + # sets the tag name for this data source # @param [Symbol] v One of the allowed_tag_names def tag_name=(v) Axlsx::RestrictionValidator.validate "#{self.class.name}.tag_name", self.class.allowed_tag_names, v @@ -45,7 +42,7 @@ module Axlsx # serialize the object # @param [String] str - def to_xml_string(str="") + def to_xml_string(str = "") str << ('<c:' << tag_name.to_s << '>') if @f str << ('<c:' << @ref_tag_name.to_s << '>') @@ -59,4 +56,3 @@ module Axlsx end end end - diff --git a/lib/axlsx/drawing/num_val.rb b/lib/axlsx/drawing/num_val.rb index b430c4b6..f4b2c399 100644 --- a/lib/axlsx/drawing/num_val.rb +++ b/lib/axlsx/drawing/num_val.rb @@ -1,9 +1,6 @@ -# -*- coding: utf-8 -*- module Axlsx - - #This class specifies data for a particular data point. + # This class specifies data for a particular data point. class NumVal < StrVal - # A string representing the format code to apply. # For more information see see the SpreadsheetML numFmt element's (§18.8.30) formatCode attribute. # @return [String] @@ -12,7 +9,7 @@ module Axlsx # creates a new NumVal object # @option options [String] formatCode # @option options [Integer] v - def initialize(options={}) + def initialize(options = {}) @format_code = "General" super(options) end diff --git a/lib/axlsx/drawing/one_cell_anchor.rb b/lib/axlsx/drawing/one_cell_anchor.rb index ffa10a7d..52cf2244 100644 --- a/lib/axlsx/drawing/one_cell_anchor.rb +++ b/lib/axlsx/drawing/one_cell_anchor.rb @@ -1,11 +1,9 @@ -# encoding: UTF-8 module Axlsx # This class details a single cell anchor for drawings. # @note The recommended way to manage drawings, images and charts is Worksheet#add_chart or Worksheet#add_image. # @see Worksheet#add_chart # @see Worksheet#add_image class OneCellAnchor - include Axlsx::OptionsParser # Creates a new OneCellAnchor object and an Pic associated with it. @@ -16,7 +14,7 @@ module Axlsx # @option options [String] image_src the file location of the image you will render # @option options [String] name the name attribute for the rendered image # @option options [String] descr the description of the image rendered - def initialize(drawing, options={}) + def initialize(drawing, options = {}) @drawing = drawing @width = 0 @height = 0 @@ -54,9 +52,10 @@ module Axlsx # We just 'figure it out' for you. # @param [Array, String, Cell, Integer] x Accepts many inputs for defining the starting position of the cell. # @param [Integer] y When x is an integer, this value is used for the row index at which the anchor starts. - def start_at(x, y=0) + def start_at(x, y = 0) from.coord x, y end + # # @see height def height=(v) Axlsx::validate_unsigned_int(v); @height = v; end @@ -92,8 +91,7 @@ module Axlsx def ext cy = @height * 914400 / 96 cx = @width * 914400 / 96 - {:cy=>cy, :cx=>cx} + { :cy => cy, :cx => cx } end - end end diff --git a/lib/axlsx/drawing/pic.rb b/lib/axlsx/drawing/pic.rb index e8d0ebd7..fb4d01fe 100644 --- a/lib/axlsx/drawing/pic.rb +++ b/lib/axlsx/drawing/pic.rb @@ -1,10 +1,8 @@ -# encoding: UTF-8 module Axlsx # a Pic object represents an image in your worksheet # Worksheet#add_image is the recommended way to manage images in your sheets # @see Worksheet#add_image class Pic - include Axlsx::OptionsParser # Creates a new Pic(ture) object @@ -16,7 +14,7 @@ module Axlsx # @option options [Integer] :width # @option options [Integer] :height # @option options [Float] :opacity - set the picture opacity, accepts a value between 0.0 and 1.0 - def initialize(anchor, options={}) + def initialize(anchor, options = {}) @anchor = anchor @hyperlink = nil @anchor.drawing.worksheet.workbook.images << self @@ -59,7 +57,7 @@ module Axlsx # sets or updates a hyperlink for this image. # @param [String] v The href value for the hyper link # @option options @see Hyperlink#initialize All options available to the Hyperlink class apply - however href will be overridden with the v parameter value. - def hyperlink=(v, options={}) + def hyperlink=(v, options = {}) options[:href] = v if hyperlink.is_a?(Hyperlink) options.each do |o| @@ -75,6 +73,7 @@ module Axlsx Axlsx::validate_string(v) RestrictionValidator.validate 'Pic.image_src', ALLOWED_MIME_TYPES, MimeTypeUtils.get_mime_type(v) raise ArgumentError, "File does not exist" unless File.exist?(v) + @image_src = v end @@ -105,7 +104,7 @@ module Axlsx # The part name for this image used in serialization and relationship building # @return [String] def pn - "#{IMAGE_PN % [(index+1), extname]}" + "#{IMAGE_PN % [(index + 1), extname]}" end # The relationship object for this pic. @@ -118,6 +117,7 @@ module Axlsx # @see OneCellAnchor.width def width return unless @anchor.is_a?(OneCellAnchor) + @anchor.width end @@ -147,7 +147,7 @@ module Axlsx # @param [Integer] x The column # @param [Integer] y The row # @return [Marker] - def start_at(x, y=nil) + def start_at(x, y = nil) @anchor.start_at x, y @anchor.from end @@ -156,7 +156,7 @@ module Axlsx # @param [Integer] x The column # @param [Integer] y The row # @return [Marker] - def end_at(x, y=nil) + def end_at(x, y = nil) use_two_cell_anchor unless @anchor.is_a?(TwoCellAnchor) @anchor.end_at x, y @anchor.to @@ -189,13 +189,15 @@ module Axlsx # Changes the anchor to a one cell anchor. def use_one_cell_anchor return if @anchor.is_a?(OneCellAnchor) + new_anchor = OneCellAnchor.new(@anchor.drawing, :start_at => [@anchor.from.col, @anchor.from.row]) swap_anchor(new_anchor) end - #changes the anchor type to a two cell anchor + # changes the anchor type to a two cell anchor def use_two_cell_anchor return if @anchor.is_a?(TwoCellAnchor) + new_anchor = TwoCellAnchor.new(@anchor.drawing, :start_at => [@anchor.from.col, @anchor.from.row]) swap_anchor(new_anchor) end diff --git a/lib/axlsx/drawing/picture_locking.rb b/lib/axlsx/drawing/picture_locking.rb index d97fb6c2..efd85f97 100644 --- a/lib/axlsx/drawing/picture_locking.rb +++ b/lib/axlsx/drawing/picture_locking.rb @@ -1,15 +1,13 @@ -# encoding: UTF-8 module Axlsx # The picture locking class defines the locking properties for pictures in your workbook. class PictureLocking - include Axlsx::OptionsParser include Axlsx::SerializedAttributes include Axlsx::Accessors boolean_attr_accessor :noGrp, :noSelect, :noRot, :noChangeAspect, - :noMove, :noResize, :noEditPoints, :noAdjustHandles, - :noChangeArrowheads, :noChangeShapeType + :noMove, :noResize, :noEditPoints, :noAdjustHandles, + :noChangeArrowheads, :noChangeShapeType serializable_attributes :noGrp, :noSelect, :noRot, :noChangeAspect, :noMove, :noResize, :noEditPoints, :noAdjustHandles, @@ -26,7 +24,7 @@ module Axlsx # @option options [Boolean] noAdjustHandles # @option options [Boolean] noChangeArrowheads # @option options [Boolean] noChangeShapeType - def initialize(options={}) + def initialize(options = {}) @noChangeAspect = true parse_options options end @@ -37,6 +35,5 @@ module Axlsx def to_xml_string(str = '') serialized_tag('a:picLocks', str) end - end end diff --git a/lib/axlsx/drawing/pie_3D_chart.rb b/lib/axlsx/drawing/pie_3D_chart.rb index f87e6d4e..1772c537 100644 --- a/lib/axlsx/drawing/pie_3D_chart.rb +++ b/lib/axlsx/drawing/pie_3D_chart.rb @@ -1,13 +1,9 @@ -# encoding: UTF-8 module Axlsx - - # The Pie3DChart is a three dimentional piechart (who would have guessed?) that you can add to your worksheet. # @see Worksheet#add_chart # @see Chart#add_series # @see README for an example class Pie3DChart < Chart - # Creates a new pie chart object # @param [GraphicFrame] frame The workbook that owns this chart. # @option options [Cell, String] title @@ -22,11 +18,11 @@ module Axlsx # @option options [Integer] perspective # @see Chart # @see View3D - def initialize(frame, options={}) + def initialize(frame, options = {}) @vary_colors = true super(frame, options) @series_type = PieSeries - @view_3D = View3D.new({:rot_x =>30, :perspective=>30}.merge(options)) + @view_3D = View3D.new({ :rot_x => 30, :perspective => 30 }.merge(options)) @d_lbls = nil end @@ -42,6 +38,5 @@ module Axlsx str << '</c:pie3DChart>' end end - end end diff --git a/lib/axlsx/drawing/pie_series.rb b/lib/axlsx/drawing/pie_series.rb index fd18ed6a..29b71e36 100644 --- a/lib/axlsx/drawing/pie_series.rb +++ b/lib/axlsx/drawing/pie_series.rb @@ -1,12 +1,9 @@ -# encoding: UTF-8 module Axlsx - # A PieSeries defines the data and labels and explosion for pie charts series. # @note The recommended way to manage series is to use Chart#add_series # @see Worksheet#add_chart # @see Chart#add_series class PieSeries < Series - # The data for this series. # @return [SimpleTypedList] attr_reader :data @@ -28,7 +25,7 @@ module Axlsx # @option options [String] title # @option options [Integer] explosion # @param [Chart] chart - def initialize(chart, options={}) + def initialize(chart, options = {}) @explosion = nil @colors = [] super(chart, options) @@ -68,7 +65,5 @@ module Axlsx # assigns the labels for this series def labels=(v) DataTypeValidator.validate "Series.labels", [AxDataSource], v; @labels = v; end - end - end diff --git a/lib/axlsx/drawing/scaling.rb b/lib/axlsx/drawing/scaling.rb index 4c9d6888..8d2d8ed7 100644 --- a/lib/axlsx/drawing/scaling.rb +++ b/lib/axlsx/drawing/scaling.rb @@ -1,8 +1,6 @@ -# encoding: UTF-8 module Axlsx # The Scaling class defines axis scaling class Scaling - include Axlsx::OptionsParser # creates a new Scaling object @@ -10,7 +8,7 @@ module Axlsx # @option options [Symbol] orientation # @option options [Float] max # @option options [Float] min - def initialize(options={}) + def initialize(options = {}) @orientation = :minMax @logBase, @min, @max = nil, nil, nil parse_options options @@ -35,7 +33,7 @@ module Axlsx attr_reader :min # @see logBase - def logBase=(v) DataTypeValidator.validate "Scaling.logBase", [Integer], v, lambda { |arg| arg >= 2 && arg <= 1000}; @logBase = v; end + def logBase=(v) DataTypeValidator.validate "Scaling.logBase", [Integer], v, lambda { |arg| arg >= 2 && arg <= 1000 }; @logBase = v; end # @see orientation def orientation=(v) RestrictionValidator.validate "Scaling.orientation", [:minMax, :maxMin], v; @orientation = v; end # @see max @@ -55,6 +53,5 @@ module Axlsx str << ('<c:max val="' << @max.to_s << '"/>') unless @max.nil? str << '</c:scaling>' end - end end diff --git a/lib/axlsx/drawing/scatter_chart.rb b/lib/axlsx/drawing/scatter_chart.rb index f3df1b3e..b118a09a 100644 --- a/lib/axlsx/drawing/scatter_chart.rb +++ b/lib/axlsx/drawing/scatter_chart.rb @@ -1,12 +1,9 @@ -# encoding: UTF-8 module Axlsx - # The ScatterChart allows you to insert a scatter chart into your worksheet # @see Worksheet#add_chart # @see Chart#add_series # @see README for an example class ScatterChart < Chart - include Axlsx::OptionsParser # The Style for the scatter chart @@ -30,11 +27,11 @@ module Axlsx alias :yValAxis :y_val_axis # Creates a new scatter chart - def initialize(frame, options={}) + def initialize(frame, options = {}) @vary_colors = 0 @scatter_style = :lineMarker - super(frame, options) + super(frame, options) @series_type = ScatterSeries @d_lbls = nil parse_options options diff --git a/lib/axlsx/drawing/scatter_series.rb b/lib/axlsx/drawing/scatter_series.rb index 8158c373..e4e1f27a 100644 --- a/lib/axlsx/drawing/scatter_series.rb +++ b/lib/axlsx/drawing/scatter_series.rb @@ -1,13 +1,10 @@ -# encoding: UTF-8 module Axlsx - # A ScatterSeries defines the x and y position of data in the chart # @note The recommended way to manage series is to use Chart#add_series # @see Worksheet#add_chart # @see Chart#add_series # @see examples/example.rb class ScatterSeries < Series - # The x data for this series. # @return [NamedAxisData] attr_reader :xData @@ -37,7 +34,7 @@ module Axlsx attr_reader :marker_symbol # Creates a new ScatterSeries - def initialize(chart, options={}) + def initialize(chart, options = {}) @xData, @yData = nil if options[:smooth].nil? # If caller hasn't specified smoothing or not, turn smoothing on or off based on scatter style @@ -53,7 +50,7 @@ module Axlsx super(chart, options) @xData = AxDataSource.new(:tag_name => :xVal, :data => options[:xData]) unless options[:xData].nil? - @yData = NumDataSource.new({:tag_name => :yVal, :data => options[:yData]}) unless options[:yData].nil? + @yData = NumDataSource.new({ :tag_name => :yVal, :data => options[:yData] }) unless options[:yData].nil? end # @see color diff --git a/lib/axlsx/drawing/ser_axis.rb b/lib/axlsx/drawing/ser_axis.rb index fd7f7602..f49c1301 100644 --- a/lib/axlsx/drawing/ser_axis.rb +++ b/lib/axlsx/drawing/ser_axis.rb @@ -1,8 +1,6 @@ -# encoding: UTF-8 module Axlsx - #A SerAxis object defines a series axis + # A SerAxis object defines a series axis class SerAxis < Axis - # The number of tick lables to skip between labels # @return [Integer] attr_reader :tick_lbl_skip @@ -16,7 +14,7 @@ module Axlsx # Creates a new SerAxis object # @option options [Integer] tick_lbl_skip # @option options [Integer] tick_mark_skip - def initialize(options={}) + def initialize(options = {}) @tick_lbl_skip, @tick_mark_skip = 1, 1 super(options) end @@ -40,6 +38,4 @@ module Axlsx str << '</c:serAx>' end end - - end diff --git a/lib/axlsx/drawing/series.rb b/lib/axlsx/drawing/series.rb index 0218f5ce..86b85f4c 100644 --- a/lib/axlsx/drawing/series.rb +++ b/lib/axlsx/drawing/series.rb @@ -1,11 +1,9 @@ -# encoding: UTF-8 module Axlsx # A Series defines the common series attributes and is the super class for all concrete series types. # @note The recommended way to manage series is to use Chart#add_series # @see Worksheet#add_chart # @see Chart#add_series class Series - include Axlsx::OptionsParser # The chart that owns this series @@ -20,7 +18,7 @@ module Axlsx # @param [Chart] chart # @option options [Integer] order # @option options [String] title - def initialize(chart, options={}) + def initialize(chart, options = {}) @order = nil self.chart = chart @chart.series << self @@ -40,7 +38,7 @@ module Axlsx end # @see order - def order=(v) Axlsx::validate_unsigned_int(v); @order = v; end + def order=(v) Axlsx::validate_unsigned_int(v); @order = v; end # @see title def title=(v) @@ -52,7 +50,7 @@ module Axlsx private # assigns the chart for this series - def chart=(v) DataTypeValidator.validate "Series.chart", Chart, v; @chart = v; end + def chart=(v) DataTypeValidator.validate "Series.chart", Chart, v; @chart = v; end # Serializes the object # @param [String] str diff --git a/lib/axlsx/drawing/series_title.rb b/lib/axlsx/drawing/series_title.rb index 2e730dea..f18be178 100644 --- a/lib/axlsx/drawing/series_title.rb +++ b/lib/axlsx/drawing/series_title.rb @@ -1,8 +1,6 @@ -# encoding: UTF-8 module Axlsx # A series title is a Title with a slightly different serialization than chart titles. class SeriesTitle < Title - # Serializes the object # @param [String] str # @return [String] diff --git a/lib/axlsx/drawing/str_data.rb b/lib/axlsx/drawing/str_data.rb index 4da69ec0..5ea8a892 100644 --- a/lib/axlsx/drawing/str_data.rb +++ b/lib/axlsx/drawing/str_data.rb @@ -1,16 +1,13 @@ -# -*- coding: utf-8 -*- module Axlsx - - #This specifies the last string data used for a chart. (e.g. strLit and strCache) + # This specifies the last string data used for a chart. (e.g. strLit and strCache) # This class is extended for NumData to include the formatCode attribute required for numLit and numCache class StrData - include Axlsx::OptionsParser # creates a new StrVal object # @option options [Array] :data # @option options [String] :tag_name - def initialize(options={}) + def initialize(options = {}) @tag_prefix = :str @type = StrVal @pt = SimpleTypedList.new(@type) @@ -19,7 +16,7 @@ module Axlsx # Creates the val objects for this data set. I am not overly confident this is going to play nicely with time and data types. # @param [Array] values An array of cells or values. - def data=(values=[]) + def data=(values = []) @tag_name = values.first.is_a?(Cell) ? :strCache : :strLit values.each do |value| v = value.is_a?(Cell) ? value.value : value @@ -36,7 +33,5 @@ module Axlsx end str << ('</c:' << @tag_name.to_s << '>') end - end - end diff --git a/lib/axlsx/drawing/str_val.rb b/lib/axlsx/drawing/str_val.rb index 0687833e..e5c851ee 100644 --- a/lib/axlsx/drawing/str_val.rb +++ b/lib/axlsx/drawing/str_val.rb @@ -1,14 +1,11 @@ -# -*- coding: utf-8 -*- module Axlsx - - #This class specifies data for a particular data point. + # This class specifies data for a particular data point. class StrVal - include Axlsx::OptionsParser # creates a new StrVal object # @option options [String] v - def initialize(options={}) + def initialize(options = {}) @v = "" @idx = 0 parse_options options diff --git a/lib/axlsx/drawing/title.rb b/lib/axlsx/drawing/title.rb index 88c2f92c..92294a06 100644 --- a/lib/axlsx/drawing/title.rb +++ b/lib/axlsx/drawing/title.rb @@ -1,8 +1,6 @@ -# encoding: UTF-8 module Axlsx # A Title stores information about the title of a chart class Title - # The text to be shown. Setting this property directly with a string will remove the cell reference. # @return [String] attr_reader :text @@ -17,7 +15,7 @@ module Axlsx # Creates a new Title object # @param [String, Cell] title The cell or string to be used for the chart's title - def initialize(title="", title_size="") + def initialize(title = "", title_size = "") self.cell = title if title.is_a?(Cell) self.text = title.to_s unless title.is_a?(Cell) if title_size.to_s.empty? @@ -62,9 +60,9 @@ module Axlsx end # Not implemented at this time. - #def layout=(v) DataTypeValidator.validate 'Title.layout', Layout, v; @layout = v; end - #def overlay=(v) Axlsx::validate_boolean v; @overlay=v; end - #def spPr=(v) DataTypeValidator.validate 'Title.spPr', SpPr, v; @spPr = v; end + # def layout=(v) DataTypeValidator.validate 'Title.layout', Layout, v; @layout = v; end + # def overlay=(v) Axlsx::validate_boolean v; @overlay=v; end + # def spPr=(v) DataTypeValidator.validate 'Title.spPr', SpPr, v; @spPr = v; end # Serializes the object # @param [String] str @@ -86,14 +84,14 @@ module Axlsx str << '</c:strRef>' else str << '<c:rich>' - str << '<a:bodyPr/>' - str << '<a:lstStyle/>' - str << '<a:p>' - str << '<a:r>' - str << ('<a:rPr sz="' << @text_size.to_s << '"/>') - str << ('<a:t>' << clean_value << '</a:t>') - str << '</a:r>' - str << '</a:p>' + str << '<a:bodyPr/>' + str << '<a:lstStyle/>' + str << '<a:p>' + str << '<a:r>' + str << ('<a:rPr sz="' << @text_size.to_s << '"/>') + str << ('<a:t>' << clean_value << '</a:t>') + str << '</a:r>' + str << '</a:p>' str << '</c:rich>' end str << '</c:tx>' @@ -102,6 +100,5 @@ module Axlsx str << '<c:overlay val="0"/>' str << '</c:title>' end - end end diff --git a/lib/axlsx/drawing/two_cell_anchor.rb b/lib/axlsx/drawing/two_cell_anchor.rb index d422c0ce..7b77de13 100644 --- a/lib/axlsx/drawing/two_cell_anchor.rb +++ b/lib/axlsx/drawing/two_cell_anchor.rb @@ -1,10 +1,8 @@ -# encoding: UTF-8 module Axlsx # This class details the anchor points for drawings. # @note The recommended way to manage drawings and charts is Worksheet#add_chart. Anchors are specified by the :start_at and :end_at options to that method. # @see Worksheet#add_chart class TwoCellAnchor - include Axlsx::OptionsParser # A marker that defines the from cell anchor. The default from column and row are 0 and 0 respectively @@ -32,10 +30,10 @@ module Axlsx # @param [Drawing] drawing # @option options [Array] :start_at the col, row to start at THIS IS DOCUMENTED BUT NOT IMPLEMENTED HERE! # @option options [Array] :end_at the col, row to end at - def initialize(drawing, options={}) + def initialize(drawing, options = {}) @drawing = drawing drawing.anchors << self - @from, @to = Marker.new, Marker.new(:col => 5, :row=>10) + @from, @to = Marker.new, Marker.new(:col => 5, :row => 10) parse_options options # bit of a hack to work around the fact that the coords for start at and end at @@ -48,7 +46,7 @@ module Axlsx # @note The recommended way to set the start position for graphical # objects is directly thru the object. # @see Chart#start_at - def start_at(x, y=nil) + def start_at(x, y = nil) from.coord x, y end @@ -56,7 +54,7 @@ module Axlsx # @note the recommended way to set the to position for graphical # objects is directly thru the object # @see Char#end_at - def end_at(x, y=nil) + def end_at(x, y = nil) to.coord x, y end @@ -68,7 +66,7 @@ module Axlsx end # Creates an image associated with this anchor. - def add_pic(options={}) + def add_pic(options = {}) @object = Pic.new(self, options) end diff --git a/lib/axlsx/drawing/val_axis.rb b/lib/axlsx/drawing/val_axis.rb index 430cf70f..8cd131cc 100644 --- a/lib/axlsx/drawing/val_axis.rb +++ b/lib/axlsx/drawing/val_axis.rb @@ -1,8 +1,6 @@ -# encoding: UTF-8 module Axlsx # the ValAxis class defines a chart value axis. class ValAxis < Axis - # This element specifies how the value axis crosses the category axis. # must be one of [:between, :midCat] # @return [Symbol] @@ -11,7 +9,7 @@ module Axlsx # Creates a new ValAxis object # @option options [Symbol] crosses_between - def initialize(options={}) + def initialize(options = {}) self.cross_between = :between super(options) end @@ -32,6 +30,5 @@ module Axlsx str << ('<c:crossBetween val="' << @cross_between.to_s << '"/>') str << '</c:valAx>' end - end end diff --git a/lib/axlsx/drawing/view_3D.rb b/lib/axlsx/drawing/view_3D.rb index 2223d501..1f701f32 100644 --- a/lib/axlsx/drawing/view_3D.rb +++ b/lib/axlsx/drawing/view_3D.rb @@ -1,8 +1,6 @@ -# encoding: UTF-8 module Axlsx # 3D attributes for a chart. class View3D - include Axlsx::OptionsParser # Creates a new View3D for charts @@ -12,8 +10,8 @@ module Axlsx # @option options [String] depth_percent # @option options [Boolean] r_ang_ax # @option options [Integer] perspective - def initialize(options={}) - @rot_x, @h_percent, @rot_y, @depth_percent, @r_ang_ax, @perspective = nil, nil, nil, nil, nil, nil + def initialize(options = {}) + @rot_x, @h_percent, @rot_y, @depth_percent, @r_ang_ax, @perspective = nil, nil, nil, nil, nil, nil parse_options options end @@ -63,33 +61,33 @@ module Axlsx end alias :rotX= :rot_x= - # @see h_percent - def h_percent=(v) - RegexValidator.validate "#{self.class}.h_percent", H_PERCENT_REGEX, v - @h_percent = v - end + # @see h_percent + def h_percent=(v) + RegexValidator.validate "#{self.class}.h_percent", H_PERCENT_REGEX, v + @h_percent = v + end alias :hPercent= :h_percent= - # @see rot_y - def rot_y=(v) - RangeValidator.validate "View3D.rot_y", 0, 360, v - @rot_y = v - end + # @see rot_y + def rot_y=(v) + RangeValidator.validate "View3D.rot_y", 0, 360, v + @rot_y = v + end alias :rotY= :rot_y= - # @see depth_percent - def depth_percent=(v) RegexValidator.validate "#{self.class}.depth_percent", DEPTH_PERCENT_REGEX, v; @depth_percent = v; end + # @see depth_percent + def depth_percent=(v) RegexValidator.validate "#{self.class}.depth_percent", DEPTH_PERCENT_REGEX, v; @depth_percent = v; end alias :depthPercent= :depth_percent= - # @see r_ang_ax - def r_ang_ax=(v) Axlsx::validate_boolean(v); @r_ang_ax = v; end + # @see r_ang_ax + def r_ang_ax=(v) Axlsx::validate_boolean(v); @r_ang_ax = v; end alias :rAngAx= :r_ang_ax= - # @see perspective - def perspective=(v) - RangeValidator.validate "View3D.perspective", 0, 240, v - @perspective = v - end + # @see perspective + def perspective=(v) + RangeValidator.validate "View3D.perspective", 0, 240, v + @perspective = v + end # DataTypeValidator.validate "#{self.class}.perspective", [Integer], v, lambda {|arg| arg >= 0 && arg <= 240 }; @perspective = v; end @@ -105,10 +103,12 @@ module Axlsx end private + # Note: move this to Axlsx module if we find the smae pattern elsewhere. - def element_for_attribute(name, namespace='') + def element_for_attribute(name, namespace = '') val = Axlsx.instance_values_for(self)[name] return "" if val == nil + "<%s:%s val='%s'/>" % [namespace, Axlsx::camel(name, false), val] end end diff --git a/lib/axlsx/drawing/vml_drawing.rb b/lib/axlsx/drawing/vml_drawing.rb index ac39c63d..4e9c5b0d 100644 --- a/lib/axlsx/drawing/vml_drawing.rb +++ b/lib/axlsx/drawing/vml_drawing.rb @@ -1,12 +1,11 @@ module Axlsx - # a vml drawing used for comments in excel. class VmlDrawing - # creates a new Vml Drawing object. # @param [Comments] comments the comments object this drawing is associated with def initialize(comments) raise ArgumentError, "you must provide a comments object" unless comments.is_a?(Comments) + @comments = comments end @@ -25,7 +24,7 @@ module Axlsx xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel"> <o:shapelayout v:ext="edit"> - <o:idmap v:ext="edit" data="#{@comments.worksheet.index+1}"/> + <o:idmap v:ext="edit" data="#{@comments.worksheet.index + 1}"/> </o:shapelayout> <v:shapetype id="_x0000_t202" coordsize="21600,21600" o:spt="202" path="m0,0l0,21600,21600,21600,21600,0xe"> @@ -35,8 +34,6 @@ module Axlsx BAD_PROGRAMMER @comments.each { |comment| comment.vml_shape.to_xml_string str } str << "</xml>" - end - end end diff --git a/lib/axlsx/drawing/vml_shape.rb b/lib/axlsx/drawing/vml_shape.rb index 21cac911..fd335d95 100644 --- a/lib/axlsx/drawing/vml_shape.rb +++ b/lib/axlsx/drawing/vml_shape.rb @@ -1,8 +1,6 @@ module Axlsx - # A VmlShape is used to position and render a comment. class VmlShape - include Axlsx::OptionsParser include Axlsx::Accessors @@ -17,14 +15,14 @@ module Axlsx # @option options [Integer] right_offset # @option options [Integer] bottom_row # @option options [Integer] bottom_offset - def initialize(options={}) + def initialize(options = {}) @row = @column = @left_column = @top_row = @right_column = @bottom_row = 0 @left_offset = 15 @top_offset = 2 @right_offset = 50 @bottom_offset = 5 @visible = true - @id = (0...8).map{65.+(rand(25)).chr}.join + @id = (0...8).map { 65.+(rand(25)).chr }.join parse_options options yield self if block_given? end @@ -37,8 +35,8 @@ module Axlsx # serialize the shape to a string # @param [String] str # @return [String] - def to_xml_string(str ='') -str << <<SHAME_ON_YOU + def to_xml_string(str = '') + str << <<SHAME_ON_YOU <v:shape id="#{@id}" type="#_x0000_t202" fillcolor="#ffffa1 [80]" o:insetmode="auto" style="visibility:#{@visible ? 'visible' : 'hidden'}"> @@ -60,7 +58,6 @@ str << <<SHAME_ON_YOU </x:ClientData> </v:shape> SHAME_ON_YOU - end end end diff --git a/lib/axlsx/package.rb b/lib/axlsx/package.rb index be34788b..2118d0ea 100644 --- a/lib/axlsx/package.rb +++ b/lib/axlsx/package.rb @@ -1,4 +1,3 @@ -# encoding: utf-8 module Axlsx # Package is responsible for managing all the bits and peices that Open Office XML requires to make a valid # xlsx document including validation and serialization. @@ -20,7 +19,7 @@ module Axlsx # @option options [Time] :created_at Timestamp in the document properties (defaults to current time). # @option options [Boolean] :use_shared_strings This is passed to the workbook to specify that shared strings should be used when serializing the package. # @example Package.new :author => 'you!', :workbook => Workbook.new - def initialize(options={}) + def initialize(options = {}) @workbook = nil @core, @app = Core.new, App.new @core.creator = options[:author] || @core.creator @@ -36,8 +35,6 @@ module Axlsx workbook.use_autowidth = v end - - # Shortcut to determine if the workbook is configured to use shared strings # @see Workbook#use_shared_strings def use_shared_strings @@ -50,6 +47,7 @@ module Axlsx Axlsx::validate_boolean(v); workbook.use_shared_strings = v end + # The workbook this package will serialize or validate. # @return [Workbook] If no workbook instance has been assigned with this package a new Workbook instance is returned. # @raise ArgumentError if workbook parameter is not a Workbook instance. @@ -102,11 +100,12 @@ module Axlsx # File.open('example_streamed.xlsx', 'wb') { |f| f.write(s.read) } def serialize(output, options = {}, secondary_options = nil) if !workbook.styles_applied - workbook.apply_styles + workbook.apply_styles end confirm_valid, zip_command = parse_serialize_options(options, secondary_options) return false unless !confirm_valid || self.validate.empty? + zip_provider = if zip_command ZipCommand.new(zip_command) else @@ -121,16 +120,16 @@ module Axlsx Relationship.clear_ids_cache end - # Serialize your workbook to a StringIO instance # @param [Boolean] confirm_valid Validate the package prior to serialization. # @return [StringIO|Boolean] False if confirm_valid and validation errors exist. rewound string IO if not. - def to_stream(confirm_valid=false) + def to_stream(confirm_valid = false) if !workbook.styles_applied - workbook.apply_styles + workbook.apply_styles end return false unless !confirm_valid || self.validate.empty? + Relationship.initialize_ids_cache zip = write_parts(Zip::OutputStream.new(StringIO.new.binmode, true)) stream = zip.close_buffer @@ -214,30 +213,29 @@ module Axlsx # @private def parts parts = [ - {:entry => "xl/#{STYLES_PN}", :doc => workbook.styles, :schema => SML_XSD}, - {:entry => CORE_PN, :doc => @core, :schema => CORE_XSD}, - {:entry => APP_PN, :doc => @app, :schema => APP_XSD}, - {:entry => WORKBOOK_RELS_PN, :doc => workbook.relationships, :schema => RELS_XSD}, - {:entry => WORKBOOK_PN, :doc => workbook, :schema => SML_XSD} + { :entry => "xl/#{STYLES_PN}", :doc => workbook.styles, :schema => SML_XSD }, + { :entry => CORE_PN, :doc => @core, :schema => CORE_XSD }, + { :entry => APP_PN, :doc => @app, :schema => APP_XSD }, + { :entry => WORKBOOK_RELS_PN, :doc => workbook.relationships, :schema => RELS_XSD }, + { :entry => WORKBOOK_PN, :doc => workbook, :schema => SML_XSD } ] workbook.drawings.each do |drawing| - parts << {:entry => "xl/#{drawing.rels_pn}", :doc => drawing.relationships, :schema => RELS_XSD} - parts << {:entry => "xl/#{drawing.pn}", :doc => drawing, :schema => DRAWING_XSD} + parts << { :entry => "xl/#{drawing.rels_pn}", :doc => drawing.relationships, :schema => RELS_XSD } + parts << { :entry => "xl/#{drawing.pn}", :doc => drawing, :schema => DRAWING_XSD } end - workbook.tables.each do |table| - parts << {:entry => "xl/#{table.pn}", :doc => table, :schema => SML_XSD} + parts << { :entry => "xl/#{table.pn}", :doc => table, :schema => SML_XSD } end workbook.pivot_tables.each do |pivot_table| cache_definition = pivot_table.cache_definition - parts << {:entry => "xl/#{pivot_table.rels_pn}", :doc => pivot_table.relationships, :schema => RELS_XSD} - parts << {:entry => "xl/#{pivot_table.pn}", :doc => pivot_table} #, :schema => SML_XSD} - parts << {:entry => "xl/#{cache_definition.pn}", :doc => cache_definition} #, :schema => SML_XSD} + parts << { :entry => "xl/#{pivot_table.rels_pn}", :doc => pivot_table.relationships, :schema => RELS_XSD } + parts << { :entry => "xl/#{pivot_table.pn}", :doc => pivot_table } # , :schema => SML_XSD} + parts << { :entry => "xl/#{cache_definition.pn}", :doc => cache_definition } # , :schema => SML_XSD} end - workbook.comments.each do|comment| + workbook.comments.each do |comment| if comment.size > 0 parts << { :entry => "xl/#{comment.pn}", :doc => comment, :schema => SML_XSD } parts << { :entry => "xl/#{comment.vml_drawing.pn}", :doc => comment.vml_drawing, :schema => nil } @@ -245,26 +243,26 @@ module Axlsx end workbook.charts.each do |chart| - parts << {:entry => "xl/#{chart.pn}", :doc => chart, :schema => DRAWING_XSD} + parts << { :entry => "xl/#{chart.pn}", :doc => chart, :schema => DRAWING_XSD } end workbook.images.each do |image| - parts << {:entry => "xl/#{image.pn}", :path => image.image_src} + parts << { :entry => "xl/#{image.pn}", :path => image.image_src } end if use_shared_strings - parts << {:entry => "xl/#{SHARED_STRINGS_PN}", :doc => workbook.shared_strings, :schema => SML_XSD} + parts << { :entry => "xl/#{SHARED_STRINGS_PN}", :doc => workbook.shared_strings, :schema => SML_XSD } end workbook.worksheets.each do |sheet| - parts << {:entry => "xl/#{sheet.rels_pn}", :doc => sheet.relationships, :schema => RELS_XSD} - parts << {:entry => "xl/#{sheet.pn}", :doc => sheet, :schema => SML_XSD} + parts << { :entry => "xl/#{sheet.rels_pn}", :doc => sheet.relationships, :schema => RELS_XSD } + parts << { :entry => "xl/#{sheet.pn}", :doc => sheet, :schema => SML_XSD } end # Sort parts for correct MIME detection [ - {:entry => CONTENT_TYPES_PN, :doc => content_types, :schema => CONTENT_TYPES_XSD}, - {:entry => RELS_PN, :doc => relationships, :schema => RELS_XSD}, + { :entry => CONTENT_TYPES_PN, :doc => content_types, :schema => CONTENT_TYPES_XSD }, + { :entry => RELS_PN, :doc => relationships, :schema => RELS_XSD }, *(parts.sort_by { |part| part[:entry] }.reverse) ] end @@ -314,8 +312,8 @@ module Axlsx workbook.comments.each do |comment| if comment.size > 0 - c_types << Axlsx::Override.new(:PartName => "/xl/#{comment.pn}", - :ContentType => COMMENT_CT) + c_types << Axlsx::Override.new(:PartName => "/xl/#{comment.pn}", + :ContentType => COMMENT_CT) end end @@ -325,18 +323,18 @@ module Axlsx workbook.worksheets.each do |sheet| c_types << Axlsx::Override.new(:PartName => "/xl/#{sheet.pn}", - :ContentType => WORKSHEET_CT) + :ContentType => WORKSHEET_CT) end exts = workbook.images.map { |image| image.extname.downcase } exts.uniq.each do |ext| - ct = if ['jpeg', 'jpg'].include?(ext) + ct = if ['jpeg', 'jpg'].include?(ext) JPEG_CT elsif ext == 'gif' GIF_CT elsif ext == 'png' PNG_CT end - c_types << Axlsx::Default.new(:ContentType => ct, :Extension => ext ) + c_types << Axlsx::Default.new(:ContentType => ct, :Extension => ext) end if use_shared_strings c_types << Axlsx::Override.new(:PartName => "/xl/#{SHARED_STRINGS_PN}", @@ -379,7 +377,7 @@ module Axlsx def parse_serialize_options(options, secondary_options) if secondary_options warn "[DEPRECATION] Axlsx::Package#serialize with 3 arguments is deprecated. " + - "Use keyword args instead e.g., package.serialize(output, confirm_valid: false, zip_command: 'zip')" + "Use keyword args instead e.g., package.serialize(output, confirm_valid: false, zip_command: 'zip')" end if options.is_a?(Hash) options.merge!(secondary_options || {}) @@ -387,10 +385,11 @@ module Axlsx if invalid_keys.any? raise ArgumentError.new("Invalid keyword arguments: #{invalid_keys}") end + [options.fetch(:confirm_valid, false), options.fetch(:zip_command, nil)] else warn "[DEPRECATION] Axlsx::Package#serialize with confirm_valid as a boolean is deprecated. " + - "Use keyword args instead e.g., package.serialize(output, confirm_valid: false)" + "Use keyword args instead e.g., package.serialize(output, confirm_valid: false)" parse_serialize_options((secondary_options || {}).merge(confirm_valid: options), nil) end end diff --git a/lib/axlsx/rels/relationship.rb b/lib/axlsx/rels/relationship.rb index 157f316e..aff9fa55 100644 --- a/lib/axlsx/rels/relationship.rb +++ b/lib/axlsx/rels/relationship.rb @@ -1,9 +1,7 @@ -# encoding: UTF-8 module Axlsx # A relationship defines a reference between package parts. # @note Packages automatically manage relationships. class Relationship - class << self # Keeps track of relationship ids in use. # @return [Array] @@ -12,27 +10,27 @@ module Axlsx end # Initialize cached ids. - # + # # This should be called before serializing a package (see {Package#serialize} and - # {Package#to_stream}) to make sure that serialization is idempotent (i.e. + # {Package#to_stream}) to make sure that serialization is idempotent (i.e. # Relationship instances are generated with the same IDs everytime the package # is serialized). def initialize_ids_cache Thread.current[:axlsx_relationship_ids_cache] = {} end - + # Clear cached ids. - # + # # This should be called after serializing a package (see {Package#serialize} and # {Package#to_stream}) to free the memory allocated for cache. - # - # Also, calling this avoids memory leaks (cached ids lingering around - # forever). + # + # Also, calling this avoids memory leaks (cached ids lingering around + # forever). def clear_ids_cache Thread.current[:axlsx_relationship_ids_cache] = nil end - - # Generate and return a unique id (eg. `rId123`) Used for setting {#Id}. + + # Generate and return a unique id (eg. `rId123`) Used for setting {#Id}. # # The generated id depends on the number of previously cached ids, so using # {clear_ids_cache} will automatically reset the generated ids, too. @@ -42,12 +40,12 @@ module Axlsx end end - # The id of the relationship (eg. "rId123"). Most instances get their own unique id. + # The id of the relationship (eg. "rId123"). Most instances get their own unique id. # However, some instances need to share the same id – see {#should_use_same_id_as?} # for details. # @return [String] attr_reader :Id - + # The location of the relationship target # @return [String] attr_reader :Target @@ -77,16 +75,16 @@ module Axlsx # The source object the relations belongs to (e.g. a hyperlink, drawing, ...). Needed when # looking up the relationship for a specific object (see {Relationships#for}). attr_reader :source_obj - - # Initializes a new relationship. + + # Initializes a new relationship. # @param [Object] source_obj see {#source_obj} # @param [String] type The type of the relationship # @param [String] target The target for the relationship # @option [Symbol] :target_mode only accepts :external. - def initialize(source_obj, type, target, options={}) + def initialize(source_obj, type, target, options = {}) @source_obj = source_obj - self.Target=target - self.Type=type + self.Target = target + self.Type = type self.TargetMode = options[:target_mode] if options[:target_mode] @Id = (self.class.ids_cache[ids_cache_key] ||= self.class.next_free_id) end @@ -103,17 +101,17 @@ module Axlsx # @param [String] str # @return [String] def to_xml_string(str = '') - h = Axlsx.instance_values_for(self).reject{|k, _| k == "source_obj"} + h = Axlsx.instance_values_for(self).reject { |k, _| k == "source_obj" } str << '<Relationship ' - str << (h.map { |key, value| '' << key.to_s << '="' << Axlsx::coder.encode(value.to_s) << '"'}.join(' ')) + str << (h.map { |key, value| '' << key.to_s << '="' << Axlsx::coder.encode(value.to_s) << '"' }.join(' ')) str << '/>' end - + # A key that determines whether this relationship should use already generated id. # # Instances designating the same relationship need to use the same id. We can not simply - # compare the {#Target} attribute, though: `foo/bar.xml`, `../foo/bar.xml`, - # `../../foo/bar.xml` etc. are all different but probably mean the same file (this + # compare the {#Target} attribute, though: `foo/bar.xml`, `../foo/bar.xml`, + # `../../foo/bar.xml` etc. are all different but probably mean the same file (this # is especially an issue for relationships in the context of pivot tables). So lets # just ignore this attribute for now (except when {#TargetMode} is set to `:External` – # then {#Target} will be an absolute URL and thus can safely be compared). @@ -125,6 +123,5 @@ module Axlsx key << self.Target if self.TargetMode == :External key end - end end diff --git a/lib/axlsx/rels/relationships.rb b/lib/axlsx/rels/relationships.rb index 5d07f612..71c4bf1e 100644 --- a/lib/axlsx/rels/relationships.rb +++ b/lib/axlsx/rels/relationships.rb @@ -1,11 +1,9 @@ -# encoding: UTF-8 module Axlsx -require 'axlsx/rels/relationship.rb' + require 'axlsx/rels/relationship.rb' # Relationships are a collection of Relations that define how package parts are related. # @note The package automatically manages releationships. class Relationships < SimpleTypedList - # Creates a new Relationships collection based on SimpleTypedList def initialize super Relationship @@ -15,7 +13,7 @@ require 'axlsx/rels/relationship.rb' # @see Relationship#source_obj # @return [Relationship] def for(source_obj) - find{ |rel| rel.source_obj == source_obj } + find { |rel| rel.source_obj == source_obj } end # serialize relationships @@ -24,9 +22,8 @@ require 'axlsx/rels/relationship.rb' def to_xml_string(str = '') str << '<?xml version="1.0" encoding="UTF-8"?>' str << ('<Relationships xmlns="' << RELS_R << '">') - each{ |rel| rel.to_xml_string(str) } + each { |rel| rel.to_xml_string(str) } str << '</Relationships>' end - end end diff --git a/lib/axlsx/stylesheet/border.rb b/lib/axlsx/stylesheet/border.rb index 0a823c7a..af564b22 100644 --- a/lib/axlsx/stylesheet/border.rb +++ b/lib/axlsx/stylesheet/border.rb @@ -1,8 +1,6 @@ -# encoding: UTF-8 module Axlsx # This class details a border used in Office Open XML spreadsheet styles. class Border - include Axlsx::SerializedAttributes include Axlsx::OptionsParser @@ -21,7 +19,7 @@ module Axlsx # # @note The recommended way to manage borders is with Style#add_style # @see Style#add_style - def initialize(options={}) + def initialize(options = {}) @prs = SimpleTypedList.new BorderPr parse_options options end @@ -68,6 +66,5 @@ module Axlsx end str << '</border>' end - end end diff --git a/lib/axlsx/stylesheet/border_pr.rb b/lib/axlsx/stylesheet/border_pr.rb index cba0e475..3f1054f2 100644 --- a/lib/axlsx/stylesheet/border_pr.rb +++ b/lib/axlsx/stylesheet/border_pr.rb @@ -1,4 +1,3 @@ -# encoding: UTF-8 module Axlsx # A border part. class BorderPr @@ -44,11 +43,11 @@ module Axlsx # @option options [Symbol] name # @option options [Symbol] style # @see Axlsx::Border - def initialize(options={}) + def initialize(options = {}) parse_options(options) - #options.each do |o| + # options.each do |o| # self.send("#{o[0]}=", o[1]) if self.respond_to? "#{o[0]}=" - #end + # end end # @see name @@ -66,6 +65,5 @@ module Axlsx @color.to_xml_string(str) if @color.is_a?(Color) str << ('</' << @name.to_s << '>') end - end end diff --git a/lib/axlsx/stylesheet/cell_alignment.rb b/lib/axlsx/stylesheet/cell_alignment.rb index 715a0b3e..906c7870 100644 --- a/lib/axlsx/stylesheet/cell_alignment.rb +++ b/lib/axlsx/stylesheet/cell_alignment.rb @@ -1,16 +1,11 @@ -# encoding: UTF-8 module Axlsx - - # CellAlignment stores information about the cell alignment of a style Xf Object. # @note Using Styles#add_style is the recommended way to manage cell alignment. # @see Styles#add_style class CellAlignment - - include Axlsx::SerializedAttributes include Axlsx::OptionsParser - + serializable_attributes :horizontal, :vertical, :text_rotation, :wrap_text, :indent, :relative_indent, :justify_last_line, :shrink_to_fit, :reading_order # Create a new cell_alignment object # @option options [Symbol] horizontal @@ -22,12 +17,10 @@ module Axlsx # @option options [Boolean] justify_last_line # @option options [Boolean] shrink_to_fit # @option options [Integer] reading_order - def initialize(options={}) + def initialize(options = {}) parse_options options end - - # The horizontal alignment of the cell. # @note # The horizontal cell alignement style must be one of @@ -127,6 +120,5 @@ module Axlsx def to_xml_string(str = '') serialized_tag('alignment', str) end - end end diff --git a/lib/axlsx/stylesheet/cell_protection.rb b/lib/axlsx/stylesheet/cell_protection.rb index ac32cb96..f040f207 100644 --- a/lib/axlsx/stylesheet/cell_protection.rb +++ b/lib/axlsx/stylesheet/cell_protection.rb @@ -1,10 +1,8 @@ -# encoding: UTF-8 module Axlsx # CellProtection stores information about locking or hiding cells in spreadsheet. # @note Using Styles#add_style is the recommended way to manage cell protection. # @see Styles#add_style class CellProtection - include Axlsx::OptionsParser include Axlsx::SerializedAttributes @@ -21,7 +19,7 @@ module Axlsx # Creates a new CellProtection # @option options [Boolean] hidden value for hidden protection # @option options [Boolean] locked value for locked protection - def initialize(options={}) + def initialize(options = {}) parse_options options end @@ -36,6 +34,5 @@ module Axlsx def to_xml_string(str = '') serialized_tag('protection', str) end - end end diff --git a/lib/axlsx/stylesheet/cell_style.rb b/lib/axlsx/stylesheet/cell_style.rb index 2e8da880..20f88133 100644 --- a/lib/axlsx/stylesheet/cell_style.rb +++ b/lib/axlsx/stylesheet/cell_style.rb @@ -1,10 +1,8 @@ -# encoding: UTF-8 module Axlsx # CellStyle defines named styles that reference defined formatting records and can be used in your worksheet. # @note Using Styles#add_style is the recommended way to manage cell styling. # @see Styles#add_style class CellStyle - include Axlsx::OptionsParser include Axlsx::SerializedAttributes @@ -15,7 +13,7 @@ module Axlsx # @option options [Integer] iLevel # @option options [Boolean] hidden # @option options [Boolean] customBuiltIn - def initialize(options={}) + def initialize(options = {}) parse_options options end @@ -47,8 +45,8 @@ module Axlsx # @return [Boolean] attr_reader :customBuiltin - # @see name - def name=(v) Axlsx::validate_string v; @name = v end + # @see name + def name=(v) Axlsx::validate_string v; @name = v end # @see xfId def xfId=(v) Axlsx::validate_unsigned_int v; @xfId = v end # @see builtinId @@ -66,7 +64,5 @@ module Axlsx def to_xml_string(str = '') serialized_tag('cellStyle', str) end - end - end diff --git a/lib/axlsx/stylesheet/color.rb b/lib/axlsx/stylesheet/color.rb index 2b6c126f..d6d204bf 100644 --- a/lib/axlsx/stylesheet/color.rb +++ b/lib/axlsx/stylesheet/color.rb @@ -1,8 +1,6 @@ -# encoding: UTF-8 module Axlsx # The color class represents a color used for borders, fills an fonts class Color - include Axlsx::OptionsParser include Axlsx::SerializedAttributes @@ -10,7 +8,7 @@ module Axlsx # @option options [Boolean] auto # @option options [String] rgb # @option options [Float] tint - def initialize(options={}) + def initialize(options = {}) @rgb = "FF000000" parse_options options end @@ -39,15 +37,16 @@ module Axlsx # no support for theme just yet # @return [Integer] - #attr_reader :theme + # attr_reader :theme # The tint value. # @note valid values are between -1.0 and 1.0 # @return [Float] attr_reader :tint - # @see auto + # @see auto def auto=(v) Axlsx::validate_boolean v; @auto = v end + # @see color def rgb=(v) Axlsx::validate_string(v) @@ -55,8 +54,10 @@ module Axlsx v = v * 3 if v.size == 2 v = v.rjust(8, 'FF') raise ArgumentError, "Invalid color rgb value: #{v}." unless v.match(/[0-9A-F]{8}/) + @rgb = v end + # @see tint def tint=(v) Axlsx::validate_float v; @tint = v end diff --git a/lib/axlsx/stylesheet/dxf.rb b/lib/axlsx/stylesheet/dxf.rb index 758b0869..516894df 100644 --- a/lib/axlsx/stylesheet/dxf.rb +++ b/lib/axlsx/stylesheet/dxf.rb @@ -1,15 +1,13 @@ -# encoding: UTF-8 module Axlsx # The Dxf class defines an incremental formatting record for use in Styles. The recommended way to manage styles for your workbook is with Styles#add_style # @see Styles#add_style class Dxf - include Axlsx::OptionsParser # The order in which the child elements is put in the XML seems to # be important for Excel CHILD_ELEMENTS = [:font, :numFmt, :fill, :alignment, :border, :protection] - #does not support extList (ExtensionList) + # does not support extList (ExtensionList) # The cell alignment for this style # @return [CellAlignment] @@ -44,7 +42,7 @@ module Axlsx # @option options [Font] font # @option options [CellAlignment] alignment # @option options [CellProtection] protection - def initialize(options={}) + def initialize(options = {}) parse_options options end @@ -73,7 +71,5 @@ module Axlsx end str << '</dxf>' end - end - end diff --git a/lib/axlsx/stylesheet/fill.rb b/lib/axlsx/stylesheet/fill.rb index 7bb5a437..aeff4867 100644 --- a/lib/axlsx/stylesheet/fill.rb +++ b/lib/axlsx/stylesheet/fill.rb @@ -1,4 +1,3 @@ -# encoding: UTF-8 module Axlsx # The Fill is a formatting object that manages the background color, and pattern for cells. # @note The recommended way to manage styles in your workbook is to use Styles#add_style. @@ -6,7 +5,6 @@ module Axlsx # @see PatternFill # @see GradientFill class Fill - # The type of fill # @return [PatternFill, GradientFill] attr_reader :fill_type @@ -29,7 +27,5 @@ module Axlsx # @see fill_type def fill_type=(v) DataTypeValidator.validate "Fill.fill_type", [PatternFill, GradientFill], v; @fill_type = v; end - - end end diff --git a/lib/axlsx/stylesheet/font.rb b/lib/axlsx/stylesheet/font.rb index 48d2b584..0f432d58 100644 --- a/lib/axlsx/stylesheet/font.rb +++ b/lib/axlsx/stylesheet/font.rb @@ -1,4 +1,3 @@ -# encoding: UTF-8 module Axlsx # The Font class details a font instance for use in styling cells. # @note The recommended way to manage fonts, and other styles is Styles#add_style @@ -21,7 +20,7 @@ module Axlsx # @option options [Boolean] extend # @option options [Color] color # @option options [Integer] sz - def initialize(options={}) + def initialize(options = {}) parse_options options end @@ -100,7 +99,7 @@ module Axlsx # The font's extend property # @return [Boolean] - attr_reader :extend + attr_reader :extend # The color of the font # @return [Color] @@ -110,7 +109,7 @@ module Axlsx # @return [Integer] attr_reader :sz - # @see name + # @see name def name=(v) Axlsx::validate_string v; @name = v end # @see charset def charset=(v) Axlsx::validate_unsigned_int v; @charset = v end @@ -120,6 +119,7 @@ module Axlsx def b=(v) Axlsx::validate_boolean v; @b = v end # @see i def i=(v) Axlsx::validate_boolean v; @i = v end + # @see u def u=(v) v = :single if (v == true || v == 1 || v == :true || v == 'true') @@ -127,6 +127,7 @@ module Axlsx Axlsx::validate_cell_u v @u = v end + # @see strike def strike=(v) Axlsx::validate_boolean v; @strike = v end # @see outline @@ -138,9 +139,9 @@ module Axlsx # @see extend def extend=(v) Axlsx::validate_boolean v; @extend = v end # @see color - def color=(v) DataTypeValidator.validate "Font.color", Color, v; @color=v end + def color=(v) DataTypeValidator.validate "Font.color", Color, v; @color = v end # @see sz - def sz=(v) Axlsx::validate_unsigned_int v; @sz=v end + def sz=(v) Axlsx::validate_unsigned_int v; @sz = v end # Serializes the object # @param [String] str diff --git a/lib/axlsx/stylesheet/gradient_fill.rb b/lib/axlsx/stylesheet/gradient_fill.rb index b077d497..f90a15d6 100644 --- a/lib/axlsx/stylesheet/gradient_fill.rb +++ b/lib/axlsx/stylesheet/gradient_fill.rb @@ -1,9 +1,7 @@ -# encoding: UTF-8 module Axlsx # A GradientFill defines the color and positioning for gradiant cell fill. # @see Open Office XML Part 1 §18.8.24 class GradientFill - include Axlsx::OptionsParser include Axlsx::SerializedAttributes @@ -14,7 +12,7 @@ module Axlsx # @option options [Float] right # @option options [Float] top # @option options [Float] bottom - def initialize(options={}) + def initialize(options = {}) options[:type] ||= :linear parse_options options @stop = SimpleTypedList.new GradientStop @@ -68,8 +66,8 @@ module Axlsx # @see right def right=(v) - validate_format_percentage "GradientFill.right", v - @right = v + validate_format_percentage "GradientFill.right", v + @right = v end # @see top @@ -86,7 +84,7 @@ module Axlsx # validates that the value provided is between 0.0 and 1.0 def validate_format_percentage(name, value) - DataTypeValidator.validate name, Float, value, lambda { |arg| arg >= 0.0 && arg <= 1.0} + DataTypeValidator.validate name, Float, value, lambda { |arg| arg >= 0.0 && arg <= 1.0 } end # Serializes the object diff --git a/lib/axlsx/stylesheet/gradient_stop.rb b/lib/axlsx/stylesheet/gradient_stop.rb index a76da6a6..2325ee66 100644 --- a/lib/axlsx/stylesheet/gradient_stop.rb +++ b/lib/axlsx/stylesheet/gradient_stop.rb @@ -1,4 +1,3 @@ -# encoding: UTF-8 module Axlsx # The GradientStop object represents a color point in a gradient. # @see Open Office XML Part 1 §18.8.24 @@ -21,9 +20,9 @@ module Axlsx end # @see color - def color=(v) DataTypeValidator.validate "GradientStop.color", Color, v; @color=v end + def color=(v) DataTypeValidator.validate "GradientStop.color", Color, v; @color = v end # @see position - def position=(v) DataTypeValidator.validate "GradientStop.position", Float, v, lambda { |arg| arg >= 0 && arg <= 1}; @position = v end + def position=(v) DataTypeValidator.validate "GradientStop.position", Float, v, lambda { |arg| arg >= 0 && arg <= 1 }; @position = v end # Serializes the object # @param [String] str diff --git a/lib/axlsx/stylesheet/num_fmt.rb b/lib/axlsx/stylesheet/num_fmt.rb index 1072d18a..388f0d59 100644 --- a/lib/axlsx/stylesheet/num_fmt.rb +++ b/lib/axlsx/stylesheet/num_fmt.rb @@ -1,9 +1,7 @@ -# encoding: UTF-8 module Axlsx # A NumFmt object defines an identifier and formatting code for data in cells. # @note The recommended way to manage styles is Styles#add_style class NumFmt - include Axlsx::OptionsParser include Axlsx::SerializedAttributes @@ -11,7 +9,7 @@ module Axlsx # @param [Hash] options Options for the number format object # @option [Integer] numFmtId The predefined format id or new format id for this format # @option [String] formatCode The format code for this number format - def initialize(options={}) + def initialize(options = {}) @numFmtId = 0 @formatCode = "" parse_options options @@ -81,6 +79,5 @@ module Axlsx end str end - end end diff --git a/lib/axlsx/stylesheet/pattern_fill.rb b/lib/axlsx/stylesheet/pattern_fill.rb index 059f15bb..3ebd4ff6 100644 --- a/lib/axlsx/stylesheet/pattern_fill.rb +++ b/lib/axlsx/stylesheet/pattern_fill.rb @@ -1,16 +1,14 @@ -# encoding: UTF-8 module Axlsx # A PatternFill is the pattern and solid fill styling for a cell. # @note The recommended way to manage styles is with Styles#add_style # @see Style#add_style class PatternFill - include Axlsx::OptionsParser # Creates a new PatternFill Object # @option options [Symbol] patternType # @option options [Color] fgColor # @option options [Color] bgColor - def initialize(options={}) + def initialize(options = {}) @patternType = :none parse_options options end @@ -49,9 +47,9 @@ module Axlsx attr_reader :patternType # @see fgColor - def fgColor=(v) DataTypeValidator.validate "PatternFill.fgColor", Color, v; @fgColor=v end + def fgColor=(v) DataTypeValidator.validate "PatternFill.fgColor", Color, v; @fgColor = v end # @see bgColor - def bgColor=(v) DataTypeValidator.validate "PatternFill.bgColor", Color, v; @bgColor=v end + def bgColor=(v) DataTypeValidator.validate "PatternFill.bgColor", Color, v; @bgColor = v end # @see patternType def patternType=(v) Axlsx::validate_pattern_type v; @patternType = v end diff --git a/lib/axlsx/stylesheet/styles.rb b/lib/axlsx/stylesheet/styles.rb index f6305fa9..ca2c7a8c 100644 --- a/lib/axlsx/stylesheet/styles.rb +++ b/lib/axlsx/stylesheet/styles.rb @@ -1,4 +1,3 @@ -# encoding: UTF-8 module Axlsx require 'axlsx/stylesheet/border.rb' require 'axlsx/stylesheet/border_pr.rb' @@ -18,7 +17,7 @@ module Axlsx require 'axlsx/stylesheet/xf.rb' require 'axlsx/stylesheet/cell_protection.rb' - #The Styles class manages worksheet styles + # The Styles class manages worksheet styles # In addition to creating the require style objects for a valid xlsx package, this class provides the key mechanism for adding styles to your workbook, and safely applying them to the cells of your worksheet. # All portions of the stylesheet are implemented here exception colors, which specify legacy and modified pallete colors, and exLst, whic is used as a future feature data storage area. # @see Office Open XML Part 1 18.8.11 for gory details on how this stuff gets put together @@ -137,7 +136,7 @@ module Axlsx # @option options [Integer] family The font family to use. # @option options [String] font_name The name of the font to use # @option options [Integer] num_fmt The number format to apply - # @option options [String] format_code The formatting to apply. + # @option options [String] format_code The formatting to apply. # @option options [Integer|Hash] border The border style to use. # borders support style, color and edges options @see parse_border_options # @option options [String] bg_color The background color to apply to the cell @@ -225,11 +224,11 @@ module Axlsx # # An index for cell styles where keys are styles codes as per Axlsx::Style and values are Cell#raw_style # The reason for the backward key/value ordering is that style lookup must be most efficient, while `add_style` can be less efficient - def add_style(options={}) + def add_style(options = {}) # Default to :xf options[:type] ||= :xf - raise ArgumentError, "Type must be one of [:xf, :dxf]" unless [:xf, :dxf].include?(options[:type] ) + raise ArgumentError, "Type must be one of [:xf, :dxf]" unless [:xf, :dxf].include?(options[:type]) if options[:border].is_a?(Hash) if options[:border][:edges] == :all @@ -241,10 +240,10 @@ module Axlsx if options[:type] == :xf # Check to see if style in cache already - - font_defaults = {name: @fonts.first.name, sz: @fonts.first.sz, family: @fonts.first.family} - raw_style = {type: :xf}.merge(font_defaults).merge(options) + font_defaults = { name: @fonts.first.name, sz: @fonts.first.sz, family: @fonts.first.family } + + raw_style = { type: :xf }.merge(font_defaults).merge(options) if raw_style[:format_code] raw_style.delete(:num_fmt) @@ -268,7 +267,7 @@ module Axlsx when :dxf style = Dxf.new :fill => fill, :font => font, :numFmt => numFmt, :border => border, :alignment => alignment, :protection => protection else - style = Xf.new :fillId=>fill || 0, :fontId=>font || 0, :numFmtId=>numFmt || 0, :borderId=>border || 0, :alignment => alignment, :protection => protection, :applyFill=>!fill.nil?, :applyFont=>!font.nil?, :applyNumberFormat =>!numFmt.nil?, :applyBorder=>!border.nil?, :applyAlignment => !alignment.nil?, :applyProtection => !protection.nil? + style = Xf.new :fillId => fill || 0, :fontId => font || 0, :numFmtId => numFmt || 0, :borderId => border || 0, :alignment => alignment, :protection => protection, :applyFill => !fill.nil?, :applyFont => !font.nil?, :applyNumberFormat => !numFmt.nil?, :applyBorder => !border.nil?, :applyAlignment => !alignment.nil?, :applyProtection => !protection.nil? end if options[:type] == :xf @@ -291,8 +290,9 @@ module Axlsx # @option options [Boolean] hide boolean value defining cell protection attribute for hiding. # @option options [Boolean] locked boolean value defining cell protection attribute for locking. # @return [CellProtection] - def parse_protection_options(options={}) + def parse_protection_options(options = {}) return if (options.keys & [:hidden, :locked]).empty? + CellProtection.new(options) end @@ -301,8 +301,9 @@ module Axlsx # @option options [Hash] alignment A hash of options to prive the CellAlignment intializer # @return [CellAlignment] # @see CellAlignment - def parse_alignment_options(options={}) + def parse_alignment_options(options = {}) return unless options[:alignment] + CellAlignment.new options[:alignment] end @@ -321,8 +322,9 @@ module Axlsx # @option options [Integer] family The font family to use. # @option options [String] font_name The name of the font to use # @return [Font|Integer] - def parse_font_options(options={}) + def parse_font_options(options = {}) return if (options.keys & [:fg_color, :sz, :b, :i, :u, :strike, :outline, :shadow, :charset, :family, :font_name]).empty? + Axlsx.instance_values_for(fonts.first).each do |key, value| # Thanks for that 1.8.7 - cant do a simple merge... options[key.to_sym] = value unless options.keys.include?(key.to_sym) @@ -337,31 +339,32 @@ module Axlsx # @note noop if :bg_color is not specified in options # @option options [String] bg_color The rgb color to apply to the fill # @return [Fill|Integer] - def parse_fill_options(options={}) + def parse_fill_options(options = {}) return unless options[:bg_color] - color = Color.new(:rgb=>options[:bg_color]) + + color = Color.new(:rgb => options[:bg_color]) dxf = options[:type] == :dxf color_key = dxf ? :bgColor : :fgColor - pattern = PatternFill.new(:patternType =>:solid, color_key=>color) + pattern = PatternFill.new(:patternType => :solid, color_key => color) fill = Fill.new(pattern) dxf ? fill : fills << fill end # parses Style#add_style options for borders. # @note noop if :border is not specified in options - # @option options [Hash|Integer] A border style definition hash or the index of an existing border. - # Border style definition hashes must include :style and :color key-value entries and - # may include an :edges entry that references an array of symbols identifying which border edges + # @option options [Hash|Integer] A border style definition hash or the index of an existing border. + # Border style definition hashes must include :style and :color key-value entries and + # may include an :edges entry that references an array of symbols identifying which border edges # you wish to apply the style or any other valid Border initializer options. # If the :edges entity is not provided the style is applied to all edges of cells that reference this style. - # Also available :border_top, :border_right, :border_bottom and :border_left options with :style and/or :color + # Also available :border_top, :border_right, :border_bottom and :border_left options with :style and/or :color # key-value entries, which override :border values. # @example # #apply a thick red border to the top and bottom # { :border => { :style => :thick, :color => "FFFF0000", :edges => [:top, :bottom] } # @return [Border|Integer] - def parse_border_options(options={}) - if options[:border].nil? && Border::EDGES.all?{|x| options["border_#{x}".to_sym].nil? } + def parse_border_options(options = {}) + if options[:border].nil? && Border::EDGES.all? { |x| options["border_#{x}".to_sym].nil? } return nil end @@ -377,7 +380,7 @@ module Axlsx end end - validate_border_hash = ->(val){ + validate_border_hash = ->(val) { if !(val.keys.include?(:style) && val.keys.include?(:color)) raise ArgumentError, (ERR_INVALID_BORDER_OPTIONS % options[:border]) end @@ -444,10 +447,10 @@ module Axlsx end border.prs << BorderPr.new({ - :name => edge, - :style => edge_b_opts[:style], - :color => Color.new(:rgb => edge_b_opts[:color]) }, - ) + :name => edge, + :style => edge_b_opts[:style], + :color => Color.new(:rgb => edge_b_opts[:color]) + }) end end @@ -462,15 +465,15 @@ module Axlsx # noop if neither :format_code or :num_format options are set. # @option options [Hash] A hash describing the :format_code and/or :num_fmt integer for the style. # @return [NumFmt|Integer] - def parse_num_fmt_options(options={}) + def parse_num_fmt_options(options = {}) return if (options.keys & [:format_code, :num_fmt]).empty? - #When the user provides format_code - we always need to create a new numFmt object - #When the type is :dxf we always need to create a new numFmt object + # When the user provides format_code - we always need to create a new numFmt object + # When the type is :dxf we always need to create a new numFmt object if options[:format_code] || options[:type] == :dxf - #If this is a standard xf we pull from numFmts the highest current and increment for num_fmt - options[:num_fmt] ||= (@numFmts.map{ |num_fmt| num_fmt.numFmtId }.max + 1) if options[:type] != :dxf - numFmt = NumFmt.new(:numFmtId => options[:num_fmt] || 0, :formatCode=> options[:format_code].to_s) + # If this is a standard xf we pull from numFmts the highest current and increment for num_fmt + options[:num_fmt] ||= (@numFmts.map { |num_fmt| num_fmt.numFmtId }.max + 1) if options[:type] != :dxf + numFmt = NumFmt.new(:numFmtId => options[:num_fmt] || 0, :formatCode => options[:format_code].to_s) options[:type] == :dxf ? numFmt : (numFmts << numFmt; numFmt.numFmtId) else options[:num_fmt] @@ -490,46 +493,47 @@ module Axlsx end private + # Creates the default set of styles the exel requires to be valid as well as setting up the # Axlsx::STYLE_THIN_BORDER def load_default_styles @numFmts = SimpleTypedList.new NumFmt, 'numFmts' - @numFmts << NumFmt.new(:numFmtId => NUM_FMT_YYYYMMDD, :formatCode=> "yyyy/mm/dd") - @numFmts << NumFmt.new(:numFmtId => NUM_FMT_YYYYMMDDHHMMSS, :formatCode=> "yyyy/mm/dd hh:mm:ss") + @numFmts << NumFmt.new(:numFmtId => NUM_FMT_YYYYMMDD, :formatCode => "yyyy/mm/dd") + @numFmts << NumFmt.new(:numFmtId => NUM_FMT_YYYYMMDDHHMMSS, :formatCode => "yyyy/mm/dd hh:mm:ss") @numFmts.lock @fonts = SimpleTypedList.new Font, 'fonts' - @fonts << Font.new(:name => "Arial", :sz => 11, :family=>1) + @fonts << Font.new(:name => "Arial", :sz => 11, :family => 1) @fonts.lock @fills = SimpleTypedList.new Fill, 'fills' - @fills << Fill.new(Axlsx::PatternFill.new(:patternType=>:none)) - @fills << Fill.new(Axlsx::PatternFill.new(:patternType=>:gray125)) + @fills << Fill.new(Axlsx::PatternFill.new(:patternType => :none)) + @fills << Fill.new(Axlsx::PatternFill.new(:patternType => :gray125)) @fills.lock @borders = SimpleTypedList.new Border, 'borders' @borders << Border.new black_border = Border.new [:left, :right, :top, :bottom].each do |item| - black_border.prs << BorderPr.new(:name=>item, :style=>:thin, :color=>Color.new(:rgb=>"FF000000")) + black_border.prs << BorderPr.new(:name => item, :style => :thin, :color => Color.new(:rgb => "FF000000")) end @borders << black_border @borders.lock @cellStyleXfs = SimpleTypedList.new Xf, "cellStyleXfs" - @cellStyleXfs << Xf.new(:borderId=>0, :numFmtId=>0, :fontId=>0, :fillId=>0) + @cellStyleXfs << Xf.new(:borderId => 0, :numFmtId => 0, :fontId => 0, :fillId => 0) @cellStyleXfs.lock @cellStyles = SimpleTypedList.new CellStyle, 'cellStyles' - @cellStyles << CellStyle.new(:name =>"Normal", :builtinId =>0, :xfId=>0) + @cellStyles << CellStyle.new(:name => "Normal", :builtinId => 0, :xfId => 0) @cellStyles.lock @cellXfs = SimpleTypedList.new Xf, "cellXfs" - @cellXfs << Xf.new(:borderId=>0, :xfId=>0, :numFmtId=>0, :fontId=>0, :fillId=>0) - @cellXfs << Xf.new(:borderId=>1, :xfId=>0, :numFmtId=>0, :fontId=>0, :fillId=>0) + @cellXfs << Xf.new(:borderId => 0, :xfId => 0, :numFmtId => 0, :fontId => 0, :fillId => 0) + @cellXfs << Xf.new(:borderId => 1, :xfId => 0, :numFmtId => 0, :fontId => 0, :fillId => 0) # default date formatting - @cellXfs << Xf.new(:borderId=>0, :xfId=>0, :numFmtId=>14, :fontId=>0, :fillId=>0, :applyNumberFormat=>1) + @cellXfs << Xf.new(:borderId => 0, :xfId => 0, :numFmtId => 14, :fontId => 0, :fillId => 0, :applyNumberFormat => 1) @cellXfs.lock @dxfs = SimpleTypedList.new(Dxf, "dxfs"); @dxfs.lock diff --git a/lib/axlsx/stylesheet/table_style.rb b/lib/axlsx/stylesheet/table_style.rb index d330beb2..f656ce3d 100644 --- a/lib/axlsx/stylesheet/table_style.rb +++ b/lib/axlsx/stylesheet/table_style.rb @@ -1,9 +1,7 @@ -# encoding: UTF-8 module Axlsx # A single table style definition and is a collection for tableStyleElements # @note Table are not supported in this version and only the defaults required for a valid workbook are created. class TableStyle < SimpleTypedList - include Axlsx::OptionsParser include Axlsx::SerializedAttributes @@ -12,7 +10,7 @@ module Axlsx # @param [String] name # @option options [Boolean] pivot # @option options [Boolean] table - def initialize(name, options={}) + def initialize(name, options = {}) self.name = name parse_options options super TableStyleElement @@ -33,22 +31,21 @@ module Axlsx attr_reader :table # @see name - def name=(v) Axlsx::validate_string v; @name=v end + def name=(v) Axlsx::validate_string v; @name = v end # @see pivot - def pivot=(v) Axlsx::validate_boolean v; @pivot=v end + def pivot=(v) Axlsx::validate_boolean v; @pivot = v end # @see table - def table=(v) Axlsx::validate_boolean v; @table=v end + def table=(v) Axlsx::validate_boolean v; @table = v end # Serializes the object # @param [String] str # @return [String] def to_xml_string(str = '') str << '<tableStyle ' - serialized_attributes str, {:count => self.size} + serialized_attributes str, { :count => self.size } str << '>' each { |table_style_el| table_style_el.to_xml_string(str) } str << '</tableStyle>' end - end end diff --git a/lib/axlsx/stylesheet/table_style_element.rb b/lib/axlsx/stylesheet/table_style_element.rb index 593c5950..845d6bac 100644 --- a/lib/axlsx/stylesheet/table_style_element.rb +++ b/lib/axlsx/stylesheet/table_style_element.rb @@ -1,9 +1,7 @@ -# encoding: UTF-8 module Axlsx # an element of style that belongs to a table style. # @note tables and table styles are not supported in this version. This class exists in preparation for that support. class TableStyleElement - include Axlsx::OptionsParser include Axlsx::SerializedAttributes @@ -11,7 +9,7 @@ module Axlsx # @option options [Symbol] type # @option options [Integer] size # @option options [Integer] dxfId - def initialize(options={}) + def initialize(options = {}) parse_options options end @@ -72,6 +70,5 @@ module Axlsx def to_xml_string(str = '') serialized_tag('tableStyleElement', str) end - end end diff --git a/lib/axlsx/stylesheet/table_styles.rb b/lib/axlsx/stylesheet/table_styles.rb index 6ef07c51..a55180a5 100644 --- a/lib/axlsx/stylesheet/table_styles.rb +++ b/lib/axlsx/stylesheet/table_styles.rb @@ -1,15 +1,13 @@ -# encoding: UTF-8 module Axlsx # TableStyles represents a collection of style definitions for table styles and pivot table styles. # @note Support for custom table styles does not exist in this version. Many of the classes required are defined in preparation for future release. Please do not attempt to add custom table styles. class TableStyles < SimpleTypedList - include Axlsx::SerializedAttributes # Creates a new TableStyles object that is a container for TableStyle objects # @option options [String] defaultTableStyle # @option options [String] defaultPivotStyle - def initialize(options={}) + def initialize(options = {}) @defaultTableStyle = options[:defaultTableStyle] || "TableStyleMedium9" @defaultPivotStyle = options[:defaultPivotStyle] || "PivotStyleLight16" super TableStyle @@ -25,7 +23,7 @@ module Axlsx # @return [String] attr_reader :defaultPivotStyle - # @see defaultTableStyle + # @see defaultTableStyle def defaultTableStyle=(v) Axlsx::validate_string(v); @defaultTableStyle = v; end # @see defaultPivotStyle def defaultPivotStyle=(v) Axlsx::validate_string(v); @defaultPivotStyle = v; end @@ -35,12 +33,10 @@ module Axlsx # @return [String] def to_xml_string(str = '') str << '<tableStyles ' - serialized_attributes str, {:count => self.size } + serialized_attributes str, { :count => self.size } str << '>' each { |table_style| table_style.to_xml_string(str) } str << '</tableStyles>' end - end - end diff --git a/lib/axlsx/stylesheet/xf.rb b/lib/axlsx/stylesheet/xf.rb index 0633da7d..e58608f7 100644 --- a/lib/axlsx/stylesheet/xf.rb +++ b/lib/axlsx/stylesheet/xf.rb @@ -1,9 +1,8 @@ -# encoding: UTF-8 module Axlsx # The Xf class defines a formatting record for use in Styles. The recommended way to manage styles for your workbook is with Styles#add_style # @see Styles#add_style class Xf - #does not support extList (ExtensionList) + # does not support extList (ExtensionList) include Axlsx::SerializedAttributes include Axlsx::OptionsParser @@ -23,7 +22,7 @@ module Axlsx # @option options [Boolean] applyProtection # @option options [CellAlignment] alignment # @option options [CellProtection] protection - def initialize(options={}) + def initialize(options = {}) parse_options options end @@ -93,7 +92,7 @@ module Axlsx # @return [Boolean] attr_reader :applyProtection - # @see Xf#alignment + # @see Xf#alignment def alignment=(v) DataTypeValidator.validate "Xf.alignment", CellAlignment, v; @alignment = v end # @see protection @@ -141,7 +140,5 @@ module Axlsx protection.to_xml_string(str) if self.protection str << '</xf>' end - - end end diff --git a/lib/axlsx/util/accessors.rb b/lib/axlsx/util/accessors.rb index a678b041..8f481e37 100644 --- a/lib/axlsx/util/accessors.rb +++ b/lib/axlsx/util/accessors.rb @@ -14,7 +14,6 @@ module Axlsx # Defines the class level xxx_attr_accessor methods module ClassMethods - # Creates one or more string validated attr_accessors # @param [Array] symbols An array of symbols representing the # names of the attributes you will add to your class. @@ -22,7 +21,6 @@ module Axlsx validated_attr_accessor(symbols, :validate_string) end - # Creates one or more usigned integer attr_accessors # @param [Array] symbols An array of symbols representing the # names of the attributes you will add to your class @@ -51,14 +49,14 @@ module Axlsx # @param [Array] symbols The names of the attributes to create # @param [String] validator The axlsx validation method to use when # validating assignation. - # @see lib/axlsx/util/validators.rb + # @see lib/axlsx/util/validators.rb def validated_attr_accessor(symbols, validator) symbols.each do |symbol| attr_reader symbol + module_eval(SETTER % [symbol, validator, symbol], __FILE__, __LINE__) end end end end end - diff --git a/lib/axlsx/util/constants.rb b/lib/axlsx/util/constants.rb index 2284a8e3..55e2b58f 100644 --- a/lib/axlsx/util/constants.rb +++ b/lib/axlsx/util/constants.rb @@ -1,5 +1,4 @@ module Axlsx - # XML Encoding ENCODING = "UTF-8".freeze @@ -96,7 +95,7 @@ module Axlsx # comment relation for nil target COMMENT_R_NULL = "http://purl.oclc.org/ooxml/officeDocument/relationships/comments".freeze - #vml drawing relation namespace + # vml drawing relation namespace VML_DRAWING_R = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing' # VML Drawing content type @@ -159,10 +158,9 @@ module Axlsx # png content type PNG_CT = "image/png".freeze - #drawing content type + # drawing content type DRAWING_CT = "application/vnd.openxmlformats-officedocument.drawing+xml".freeze - # xml content type extensions XML_EX = "xml".freeze @@ -239,7 +237,7 @@ module Axlsx COMMENT_PN = "comments%d.xml".freeze # location of schema files for validation - SCHEMA_BASE = (File.dirname(__FILE__)+'/../../schema/').freeze + SCHEMA_BASE = (File.dirname(__FILE__) + '/../../schema/').freeze # App validation schema APP_XSD = (SCHEMA_BASE + "shared-documentPropertiesExtended.xsd").freeze diff --git a/lib/axlsx/util/options_parser.rb b/lib/axlsx/util/options_parser.rb index 9b6d1766..3f2c1937 100644 --- a/lib/axlsx/util/options_parser.rb +++ b/lib/axlsx/util/options_parser.rb @@ -2,11 +2,10 @@ module Axlsx # This module defines a single method for parsing options in class # initializers. module OptionsParser - # Parses an options hash by calling any defined method by the same # name of the key postfixed with an '=' # @param [Hash] options Options to parse. - def parse_options(options={}) + def parse_options(options = {}) options.each do |key, value| key = :"#{key}=" self.send(key, value) if !value.nil? && self.respond_to?(key) diff --git a/lib/axlsx/util/serialized_attributes.rb b/lib/axlsx/util/serialized_attributes.rb index 06d1697a..eeac6e74 100644 --- a/lib/axlsx/util/serialized_attributes.rb +++ b/lib/axlsx/util/serialized_attributes.rb @@ -2,7 +2,6 @@ module Axlsx # This module allows us to define a list of symbols defining which # attributes will be serialized for a class. module SerializedAttributes - # Extend with class methods def self.included(base) base.send :extend, ClassMethods @@ -10,8 +9,7 @@ module Axlsx # class methods applied to all includers module ClassMethods - - # This is the method to be used in inheriting classes to specify + # This is the method to be used in inheriting classes to specify # which of the instance values are serializable def serializable_attributes(*symbols) @xml_attributes = symbols @@ -43,7 +41,7 @@ module Axlsx end end - # serializes the instance values of the defining object based on the + # serializes the instance values of the defining object based on the # list of serializable attributes. # @param [String] str The string instance to append this # serialization to. @@ -73,12 +71,13 @@ module Axlsx # @param [String] str The string instance to which serialized data is appended # @param [Array] additional_attributes An array of additional attribute names. # @return [String] The serialized output. - def serialized_element_attributes(str='', additional_attributes=[], &block) + def serialized_element_attributes(str = '', additional_attributes = [], &block) attrs = self.class.xml_element_attributes + additional_attributes values = Axlsx.instance_values_for(self) attrs.each do |attribute_name| value = values[attribute_name.to_s] next if value.nil? + value = yield value if block_given? element_name = Axlsx.camel(attribute_name, false) str << "<#{element_name}>#{value}</#{element_name}>" diff --git a/lib/axlsx/util/simple_typed_list.rb b/lib/axlsx/util/simple_typed_list.rb index 77bed775..51b8a8d5 100644 --- a/lib/axlsx/util/simple_typed_list.rb +++ b/lib/axlsx/util/simple_typed_list.rb @@ -1,6 +1,4 @@ -# encoding: UTF-8 module Axlsx - # A SimpleTypedList is a type restrictive collection that allows some of the methods from Array and supports basic xml serialization. # @private class SimpleTypedList @@ -8,12 +6,13 @@ module Axlsx # @param [Array, Class] type An array of Class objects or a single Class object # @param [String] serialize_as The tag name to use in serialization # @raise [ArgumentError] if all members of type are not Class objects - def initialize type, serialize_as=nil, start_size = 0 + def initialize type, serialize_as = nil, start_size = 0 if type.is_a? Array type.each { |item| raise ArgumentError, "All members of type must be Class objects" unless item.is_a? Class } @allowed_types = type else raise ArgumentError, "Type must be a Class object or array of Class objects" unless type.is_a? Class + @allowed_types = [type] end @serialize_as = serialize_as unless serialize_as.nil? @@ -39,12 +38,13 @@ module Axlsx # any non populated cell in the matrix will be a nil value def transpose return @list.clone if @list.size == 0 + row_count = @list.size - max_column_count = @list.map{|row| row.cells.size}.max + max_column_count = @list.map { |row| row.cells.size }.max result = Array.new(max_column_count) { Array.new(row_count) } # yes, I know it is silly, but that warning is really annoying row_count.times do |row_index| - max_column_count.times do |column_index| + max_column_count.times do |column_index| datum = if @list[row_index].cells.size >= max_column_count @list[row_index].cells[column_index] elsif block_given? @@ -55,7 +55,7 @@ module Axlsx end result end - + # Lock this list at the current size # @return [self] def lock @@ -69,7 +69,7 @@ module Axlsx @locked_at = nil self end - + def to_ary @list end @@ -82,9 +82,9 @@ module Axlsx # one of the allowed types # @return [SimpleTypedList] def +(v) - v.each do |item| + v.each do |item| DataTypeValidator.validate :SimpleTypedList_plus, @allowed_types, item - @list << item + @list << item end end @@ -96,10 +96,9 @@ module Axlsx DataTypeValidator.validate :SimpleTypedList_push, @allowed_types, v @list << v @list.size - 1 - end - + end + alias :push :<< - # delete the item from the list # @param [Any] v The item to be deleted. @@ -108,6 +107,7 @@ module Axlsx def delete(v) return unless include? v raise ArgumentError, "Item is protected and cannot be deleted" if protected? index(v) + @list.delete v end @@ -117,6 +117,7 @@ module Axlsx def delete_at(index) @list[index] raise ArgumentError, "Item is protected and cannot be deleted" if protected? index + @list.delete_at index end @@ -128,6 +129,7 @@ module Axlsx def []=(index, v) DataTypeValidator.validate :SimpleTypedList_insert, @allowed_types, v raise ArgumentError, "Item is protected and cannot be changed" if protected? index + @list[index] = v v end @@ -140,6 +142,7 @@ module Axlsx def insert(index, v) DataTypeValidator.validate :SimpleTypedList_insert, @allowed_types, v raise ArgumentError, "Item is protected and cannot be changed" if protected? index + @list.insert(index, v) v end @@ -148,6 +151,7 @@ module Axlsx # @param [Integer] index def protected? index return false unless locked_at.is_a? Integer + index < locked_at end @@ -164,16 +168,13 @@ module Axlsx end } end - + def to_xml_string(str = '') classname = @allowed_types[0].name.split('::').last - el_name = serialize_as.to_s || (classname[0,1].downcase + classname[1..-1]) + el_name = serialize_as.to_s || (classname[0, 1].downcase + classname[1..-1]) str << ('<' << el_name << ' count="' << size.to_s << '">') each { |item| item.to_xml_string(str) } str << ('</' << el_name << '>') end - end - - end diff --git a/lib/axlsx/util/storage.rb b/lib/axlsx/util/storage.rb index 6c16bdcf..4932c93c 100644 --- a/lib/axlsx/util/storage.rb +++ b/lib/axlsx/util/storage.rb @@ -1,61 +1,58 @@ -# encoding: UTF-8 module Axlsx - # The Storage class represents a storage object or stream in a compound file. class Storage - # Packing for the Storage when pushing an array of items into a byte stream # Name, name length, type, color, left sibling, right sibling, child, classid, state, created, modified, sector, size PACKING = "s32 s1 c2 l3 x16 x4 q2 l q".freeze # storage types TYPES = { - :root=>5, - :stream=>2, - :storage=>1 + :root => 5, + :stream => 2, + :storage => 1 }.freeze # Creates a byte string for this storage - # @return [String] + # @return [String] def to_s - data = [@name.concat(Array.new([email protected], 0)), - @name_size, - @type, - @color, - @left, - @right, - @child, - @created, - @modified, - @sector, - @size].flatten + data = [@name.concat(Array.new(32 - @name.size, 0)), + @name_size, + @type, + @color, + @left, + @right, + @child, + @created, + @modified, + @sector, + @size].flatten data.pack(PACKING) end # storage colors COLORS = { - :red=>0, - :black=>1 + :red => 0, + :black => 1 } # The color of this node in the directory tree. Defaults to black if not specified # @return [Integer] color attr_reader :color - + # Sets the color for this storage # @param [Integer] v Must be one of the COLORS constant hash values def color=(v) - RestrictionValidator.validate :storage_color, COLORS.values, v + RestrictionValidator.validate :storage_color, COLORS.values, v @color = v end # The size of the name for this node. - # interesting to see that office actually uses 'R' for the root directory and lists the size as 2 bytes - thus is it *NOT* null + # interesting to see that office actually uses 'R' for the root directory and lists the size as 2 bytes - thus is it *NOT* null # terminated. I am making this r/w so that I can override the size # @return [Integer] color attr_reader :name_size - # the name of the stream + # the name of the stream attr_reader :name # sets the name of the stream. @@ -87,16 +84,16 @@ module Axlsx # @return [Integer] sector attr_accessor :sector - # The 0 based index in the directoies chain for this the left sibling of this storage. - + # The 0 based index in the directoies chain for this the left sibling of this storage. + # @return [Integer] left - attr_accessor :left + attr_accessor :left - # The 0 based index in the directoies chain for this the right sibling of this storage. + # The 0 based index in the directoies chain for this the right sibling of this storage. # @return [Integer] right - attr_accessor :right + attr_accessor :right - # The 0 based index in the directoies chain for the child of this storage. + # The 0 based index in the directoies chain for the child of this storage. # @return [Integer] child attr_accessor :child @@ -113,14 +110,14 @@ module Axlsx # @return [Integer] type attr_reader :type - # Sets the type for this storage. - # @param [Integer] v the type to specify must be one of the TYPES constant hash values. + # Sets the type for this storage. + # @param [Integer] v the type to specify must be one of the TYPES constant hash values. def type=(v) - RestrictionValidator.validate :storage_type, TYPES.values, v + RestrictionValidator.validate :storage_type, TYPES.values, v @type = v end - # Creates a new storage object. + # Creates a new storage object. # @param [String] name the name of the storage # @option options [Integer] color (black) # @option options [Integer] type (storage) @@ -131,7 +128,7 @@ module Axlsx # @option options [Integer] created (0) # @option options [Integer] modified (0) # @option options [Integer] sector (0) - def initialize(name, options= {}) + def initialize(name, options = {}) @left = @right = @child = -1 @sector = @size = @created = @modified = 0 options.each do |o| @@ -141,6 +138,5 @@ module Axlsx @type ||= (data.nil? ? TYPES[:storage] : TYPES[:stream]) self.name = name end - end end diff --git a/lib/axlsx/util/validators.rb b/lib/axlsx/util/validators.rb index f1bf0ffc..b6877a48 100644 --- a/lib/axlsx/util/validators.rb +++ b/lib/axlsx/util/validators.rb @@ -1,4 +1,3 @@ -# encoding: UTF-8 module Axlsx # Validate a value against a specific list of allowed values. class RestrictionValidator @@ -10,6 +9,7 @@ module Axlsx # @return [Boolean] true if validation succeeds. def self.validate(name, choices, v) raise ArgumentError, (ERR_RESTRICTION % [v.to_s, name, choices.inspect]) unless choices.include?(v) + true end end @@ -32,6 +32,7 @@ module Axlsx raise ArgumentError, (ERR_RANGE % [value.inspect, min.to_s, max.to_s, inclusive]) unless passes end end + # Validates the value against the regular expression provided. class RegexValidator # @param [String] name The name of what is being validated. This is included in the output when the value is invalid @@ -51,9 +52,9 @@ module Axlsx # @raise [ArugumentError] Raised if the class of the value provided is not in the specified array of types or the block passed returns false # @return [Boolean] true if validation succeeds. # @see validate_boolean - def self.validate(name, types, v, other=false) + def self.validate(name, types, v, other = false) if other.is_a?(Proc) - raise ArgumentError, (ERR_TYPE % [v.inspect, name, types.inspect]) unless other.call(v) + raise ArgumentError, (ERR_TYPE % [v.inspect, name, types.inspect]) unless other.call(v) end v_class = v.is_a?(Class) ? v : v.class Array(types).each do |t| @@ -63,7 +64,6 @@ module Axlsx end end - # Requires that the value can be converted to an integer # @para, [Any] v the value to validate # @raise [ArgumentError] raised if the value cannot be converted to an integer @@ -144,6 +144,7 @@ module Axlsx def self.validate_page_orientation(v) RestrictionValidator.validate "page_orientation", [:default, :landscape, :portrait], v end + # Requires that the value is one of :none, :single, :double, :singleAccounting, :doubleAccounting def self.validate_cell_u(v) RestrictionValidator.validate "cell run style u", [:none, :single, :double, :singleAccounting, :doubleAccounting], v @@ -153,6 +154,7 @@ module Axlsx def self.validate_family(v) RestrictionValidator.validate "cell run style family", 1..5, v end + # Requires that the value is valid pattern type. # valid pattern types must be one of :none, :solid, :mediumGray, :darkGray, :lightGray, :darkHorizontal, :darkVertical, :darkDown, # :darkUp, :darkGrid, :darkTrellis, :lightHorizontal, :lightVertical, :lightDown, :lightUp, :lightGrid, :lightTrellis, :gray125, or :gray0625. @@ -215,6 +217,7 @@ module Axlsx def self.validate_scatter_style(v) Axlsx::RestrictionValidator.validate "ScatterChart.scatterStyle", [:none, :line, :lineMarker, :marker, :smooth, :smoothMarker], v.to_sym end + # Requires that the value is a valid horizontal_alignment # :general, :left, :center, :right, :fill, :justify, :centerContinuous, :distributed are allowed # @param [Any] v The value validated diff --git a/lib/axlsx/util/zip_command.rb b/lib/axlsx/util/zip_command.rb index fb336209..23fd7cf6 100644 --- a/lib/axlsx/util/zip_command.rb +++ b/lib/axlsx/util/zip_command.rb @@ -1,9 +1,7 @@ -# encoding: UTF-8 require 'open3' require 'shellwords' module Axlsx - # The ZipCommand class supports zipping the Excel file contents using # a binary zip program instead of RubyZip's `Zip::OutputStream`. # diff --git a/lib/axlsx/version.rb b/lib/axlsx/version.rb index 2fda2686..cf70e2e9 100644 --- a/lib/axlsx/version.rb +++ b/lib/axlsx/version.rb @@ -1,5 +1,4 @@ module Axlsx - # The current version VERSION = "3.3.0" end diff --git a/lib/axlsx/workbook/defined_name.rb b/lib/axlsx/workbook/defined_name.rb index 283a8e9d..d3b6e1ef 100644 --- a/lib/axlsx/workbook/defined_name.rb +++ b/lib/axlsx/workbook/defined_name.rb @@ -2,9 +2,9 @@ # <definedName name="_xlnm.Print_Titles" localSheetId="0">Sheet1!$1:$1</definedName> # </definedNames> -#<xsd:complexType name="CT_DefinedName"> +# <xsd:complexType name="CT_DefinedName"> # <xsd:simpleContent> -# <xsd:extension base="ST_Formula"> +#  <xsd:extension base="ST_Formula"> # <xsd:attribute name="name" type="s:ST_Xstring" use="required"/> # <xsd:attribute name="comment" type="s:ST_Xstring" use="optional"/> # <xsd:attribute name="customMenu" type="s:ST_Xstring" use="optional"/> @@ -97,7 +97,7 @@ module Axlsx # version of the workbook that is published to or rendered on a Web or application server. # @option [Boolean] workbook_parameter - Specifies a boolean value that indicates that the name is used as a workbook parameter on a # version of the workbook that is published to or rendered on a Web or application server. - def initialize(formula, options={}) + def initialize(formula, options = {}) @formula = formula parse_options options end @@ -116,10 +116,11 @@ module Axlsx boolean_attr_accessor :workbook_parameter, :publish_to_server, :xlm, :vb_proceedure, :function, :hidden serializable_attributes :short_cut_key, :status_bar, :help, :description, :custom_menu, :comment, - :workbook_parameter, :publish_to_server, :xlm, :vb_proceedure, :function, :hidden, :local_sheet_id + :workbook_parameter, :publish_to_server, :xlm, :vb_proceedure, :function, :hidden, :local_sheet_id - def to_xml_string(str='') + def to_xml_string(str = '') raise ArgumentError, 'you must specify the name for this defined name. Please read the documentation for Axlsx::DefinedName for more details' unless name + str << ('<definedName ' << 'name="' << name << '" ') serialized_attributes str str << ('>' << @formula << '</definedName>') diff --git a/lib/axlsx/workbook/defined_names.rb b/lib/axlsx/workbook/defined_names.rb index 11f10a56..017c6d96 100644 --- a/lib/axlsx/workbook/defined_names.rb +++ b/lib/axlsx/workbook/defined_names.rb @@ -1,7 +1,6 @@ module Axlsx # a simple types list of DefinedName objects class DefinedNames < SimpleTypedList - # creates the DefinedNames object def initialize super DefinedName @@ -12,10 +11,10 @@ module Axlsx # @return [String] def to_xml_string(str = '') return if empty? + str << '<definedNames>' each { |defined_name| defined_name.to_xml_string(str) } str << '</definedNames>' end end end - diff --git a/lib/axlsx/workbook/shared_strings_table.rb b/lib/axlsx/workbook/shared_strings_table.rb index 7e9402b2..b8502206 100644 --- a/lib/axlsx/workbook/shared_strings_table.rb +++ b/lib/axlsx/workbook/shared_strings_table.rb @@ -1,6 +1,4 @@ -# encoding: UTF-8 module Axlsx - # The Shared String Table class is responsible for managing and serializing common strings in a workbook. # While the ECMA-376 spec allows for both inline and shared strings it seems that at least some applications like iWorks Numbers # and Google Docs require that the shared string table is populated in order to interoperate properly. @@ -9,7 +7,6 @@ module Axlsx # @note Serialization performance is affected by using this serialization method so if you do not need interoperability # it is recomended that you use the default inline string method of serialization. class SharedStringsTable - # The total number of strings in the workbook including duplicates # Empty cells are treated as blank strings # @return [Integer] @@ -33,12 +30,12 @@ module Axlsx # Creates a new Shared Strings Table agains an array of cells # @param [Array] cells This is an array of all of the cells in the workbook # @param [Symbol] xml_space The xml:space behavior for the shared string table. - def initialize(cells, xml_space=:preserve) + def initialize(cells, xml_space = :preserve) @index = 0 @xml_space = xml_space @unique_cells = {} @shared_xml_string = "" - shareable_cells = cells.flatten.select{ |cell| cell.plain_string? || cell.contains_rich_text? } + shareable_cells = cells.flatten.select { |cell| cell.plain_string? || cell.contains_rich_text? } @count = shareable_cells.size resolve(shareable_cells) end @@ -46,7 +43,7 @@ module Axlsx # Serializes the object # @param [String] str # @return [String] - def to_xml_string(str='') + def to_xml_string(str = '') Axlsx::sanitize(@shared_xml_string) str << ('<?xml version="1.0" encoding="UTF-8"?><sst xmlns="' << XML_NS << '"') str << (' count="' << @count.to_s << '" uniqueCount="' << unique_count.to_s << '"') diff --git a/lib/axlsx/workbook/workbook.rb b/lib/axlsx/workbook/workbook.rb index 938d4aee..134a3e6b 100644 --- a/lib/axlsx/workbook/workbook.rb +++ b/lib/axlsx/workbook/workbook.rb @@ -1,65 +1,63 @@ -# -*- coding: utf-8 -*- module Axlsx -require 'axlsx/workbook/worksheet/sheet_calc_pr.rb' -require 'axlsx/workbook/worksheet/auto_filter/auto_filter.rb' -require 'axlsx/workbook/worksheet/date_time_converter.rb' -require 'axlsx/workbook/worksheet/protected_range.rb' -require 'axlsx/workbook/worksheet/protected_ranges.rb' -require 'axlsx/workbook/worksheet/rich_text_run' -require 'axlsx/workbook/worksheet/rich_text' -require 'axlsx/workbook/worksheet/cell_serializer.rb' -require 'axlsx/workbook/worksheet/cell.rb' -require 'axlsx/workbook/worksheet/page_margins.rb' -require 'axlsx/workbook/worksheet/page_set_up_pr.rb' -require 'axlsx/workbook/worksheet/outline_pr.rb' -require 'axlsx/workbook/worksheet/page_setup.rb' -require 'axlsx/workbook/worksheet/header_footer.rb' -require 'axlsx/workbook/worksheet/print_options.rb' -require 'axlsx/workbook/worksheet/cfvo.rb' -require 'axlsx/workbook/worksheet/cfvos.rb' -require 'axlsx/workbook/worksheet/color_scale.rb' -require 'axlsx/workbook/worksheet/data_bar.rb' -require 'axlsx/workbook/worksheet/icon_set.rb' -require 'axlsx/workbook/worksheet/conditional_formatting.rb' -require 'axlsx/workbook/worksheet/conditional_formatting_rule.rb' -require 'axlsx/workbook/worksheet/conditional_formattings.rb' -require 'axlsx/workbook/worksheet/row.rb' -require 'axlsx/workbook/worksheet/col.rb' -require 'axlsx/workbook/worksheet/cols.rb' -require 'axlsx/workbook/worksheet/comments.rb' -require 'axlsx/workbook/worksheet/comment.rb' -require 'axlsx/workbook/worksheet/merged_cells.rb' -require 'axlsx/workbook/worksheet/sheet_protection.rb' -require 'axlsx/workbook/worksheet/sheet_pr.rb' -require 'axlsx/workbook/worksheet/dimension.rb' -require 'axlsx/workbook/worksheet/sheet_data.rb' -require 'axlsx/workbook/worksheet/worksheet_drawing.rb' -require 'axlsx/workbook/worksheet/worksheet_comments.rb' -require 'axlsx/workbook/worksheet/worksheet_hyperlink' -require 'axlsx/workbook/worksheet/worksheet_hyperlinks' -require 'axlsx/workbook/worksheet/break' -require 'axlsx/workbook/worksheet/row_breaks' -require 'axlsx/workbook/worksheet/col_breaks' -require 'axlsx/workbook/workbook_view' -require 'axlsx/workbook/workbook_views' - - -require 'axlsx/workbook/worksheet/worksheet.rb' -require 'axlsx/workbook/shared_strings_table.rb' -require 'axlsx/workbook/defined_name.rb' -require 'axlsx/workbook/defined_names.rb' -require 'axlsx/workbook/worksheet/table_style_info.rb' -require 'axlsx/workbook/worksheet/table.rb' -require 'axlsx/workbook/worksheet/tables.rb' -require 'axlsx/workbook/worksheet/pivot_table_cache_definition.rb' -require 'axlsx/workbook/worksheet/pivot_table.rb' -require 'axlsx/workbook/worksheet/pivot_tables.rb' -require 'axlsx/workbook/worksheet/data_validation.rb' -require 'axlsx/workbook/worksheet/data_validations.rb' -require 'axlsx/workbook/worksheet/sheet_view.rb' -require 'axlsx/workbook/worksheet/sheet_format_pr.rb' -require 'axlsx/workbook/worksheet/pane.rb' -require 'axlsx/workbook/worksheet/selection.rb' + require 'axlsx/workbook/worksheet/sheet_calc_pr.rb' + require 'axlsx/workbook/worksheet/auto_filter/auto_filter.rb' + require 'axlsx/workbook/worksheet/date_time_converter.rb' + require 'axlsx/workbook/worksheet/protected_range.rb' + require 'axlsx/workbook/worksheet/protected_ranges.rb' + require 'axlsx/workbook/worksheet/rich_text_run' + require 'axlsx/workbook/worksheet/rich_text' + require 'axlsx/workbook/worksheet/cell_serializer.rb' + require 'axlsx/workbook/worksheet/cell.rb' + require 'axlsx/workbook/worksheet/page_margins.rb' + require 'axlsx/workbook/worksheet/page_set_up_pr.rb' + require 'axlsx/workbook/worksheet/outline_pr.rb' + require 'axlsx/workbook/worksheet/page_setup.rb' + require 'axlsx/workbook/worksheet/header_footer.rb' + require 'axlsx/workbook/worksheet/print_options.rb' + require 'axlsx/workbook/worksheet/cfvo.rb' + require 'axlsx/workbook/worksheet/cfvos.rb' + require 'axlsx/workbook/worksheet/color_scale.rb' + require 'axlsx/workbook/worksheet/data_bar.rb' + require 'axlsx/workbook/worksheet/icon_set.rb' + require 'axlsx/workbook/worksheet/conditional_formatting.rb' + require 'axlsx/workbook/worksheet/conditional_formatting_rule.rb' + require 'axlsx/workbook/worksheet/conditional_formattings.rb' + require 'axlsx/workbook/worksheet/row.rb' + require 'axlsx/workbook/worksheet/col.rb' + require 'axlsx/workbook/worksheet/cols.rb' + require 'axlsx/workbook/worksheet/comments.rb' + require 'axlsx/workbook/worksheet/comment.rb' + require 'axlsx/workbook/worksheet/merged_cells.rb' + require 'axlsx/workbook/worksheet/sheet_protection.rb' + require 'axlsx/workbook/worksheet/sheet_pr.rb' + require 'axlsx/workbook/worksheet/dimension.rb' + require 'axlsx/workbook/worksheet/sheet_data.rb' + require 'axlsx/workbook/worksheet/worksheet_drawing.rb' + require 'axlsx/workbook/worksheet/worksheet_comments.rb' + require 'axlsx/workbook/worksheet/worksheet_hyperlink' + require 'axlsx/workbook/worksheet/worksheet_hyperlinks' + require 'axlsx/workbook/worksheet/break' + require 'axlsx/workbook/worksheet/row_breaks' + require 'axlsx/workbook/worksheet/col_breaks' + require 'axlsx/workbook/workbook_view' + require 'axlsx/workbook/workbook_views' + + require 'axlsx/workbook/worksheet/worksheet.rb' + require 'axlsx/workbook/shared_strings_table.rb' + require 'axlsx/workbook/defined_name.rb' + require 'axlsx/workbook/defined_names.rb' + require 'axlsx/workbook/worksheet/table_style_info.rb' + require 'axlsx/workbook/worksheet/table.rb' + require 'axlsx/workbook/worksheet/tables.rb' + require 'axlsx/workbook/worksheet/pivot_table_cache_definition.rb' + require 'axlsx/workbook/worksheet/pivot_table.rb' + require 'axlsx/workbook/worksheet/pivot_tables.rb' + require 'axlsx/workbook/worksheet/data_validation.rb' + require 'axlsx/workbook/worksheet/data_validations.rb' + require 'axlsx/workbook/worksheet/sheet_view.rb' + require 'axlsx/workbook/worksheet/sheet_format_pr.rb' + require 'axlsx/workbook/worksheet/pane.rb' + require 'axlsx/workbook/worksheet/selection.rb' # The Workbook class is an xlsx workbook that manages worksheets, charts, drawings and styles. # The following parts of the Office Open XML spreadsheet specification are not implimented in this version. # @@ -84,7 +82,6 @@ require 'axlsx/workbook/worksheet/selection.rb' # # *workbookPr is only supported to the extend of date1904 class Workbook - BOLD_FONT_MULTIPLIER = 1.5 FONT_SCALE_DIVISOR = 10.0 @@ -109,8 +106,7 @@ require 'axlsx/workbook/worksheet/selection.rb' @is_reversed = v end - - # A collection of worksheets associated with this workbook. + # A collection of worksheets associated with this workbook. # @note The recommended way to manage worksheets is add_worksheet # @see Workbook#add_worksheet # @see Worksheet @@ -140,7 +136,6 @@ require 'axlsx/workbook/worksheet/selection.rb' # pretty sure this two are always empty and can be removed. - # A colllection of tables associated with this workbook # @note The recommended way to manage drawings is Worksheet#add_table # @see Worksheet#add_table @@ -217,11 +212,9 @@ require 'axlsx/workbook/worksheet/selection.rb' self.styles_applied = true end - # Indicates if the epoc date for serialization should be 1904. If false, 1900 is used. @@date1904 = false - # A quick helper to retrive a worksheet by name # @param [String] name The name of the sheet you are looking for # @return [Worksheet] The sheet found, or nil @@ -233,7 +226,7 @@ require 'axlsx/workbook/worksheet/selection.rb' # Creates a new Workbook # The recomended way to work with workbooks is via Package#workbook # @option options [Boolean] date1904. If this is not specified, date1904 is set to false. Office 2011 for Mac defaults to false. - def initialize(options={}) + def initialize(options = {}) @styles = Styles.new @worksheets = SimpleTypedList.new Worksheet @drawings = SimpleTypedList.new Drawing @@ -244,12 +237,11 @@ require 'axlsx/workbook/worksheet/selection.rb' @pivot_tables = SimpleTypedList.new PivotTable @comments = SimpleTypedList.new Comments - @use_autowidth = true @bold_font_multiplier = BOLD_FONT_MULTIPLIER @font_scale_divisor = FONT_SCALE_DIVISOR - self.date1904= !options[:date1904].nil? && options[:date1904] + self.date1904 = !options[:date1904].nil? && options[:date1904] yield self if block_given? end @@ -276,7 +268,7 @@ require 'axlsx/workbook/worksheet/selection.rb' def use_autowidth() @use_autowidth; end # see @use_autowidth - def use_autowidth=(v=true) Axlsx::validate_boolean v; @use_autowidth = v; end + def use_autowidth=(v = true) Axlsx::validate_boolean v; @use_autowidth = v; end # Font size of bold fonts is multiplied with this # Used for automatic calculation of cell widths with bold text @@ -306,7 +298,7 @@ require 'axlsx/workbook/worksheet/selection.rb' # @param [Hash] options Options to pass into the worksheed during initialization. # @option options [String] name The name of the worksheet # @option options [Hash] page_margins The page margins for the worksheet - def insert_worksheet(index=0, options={}) + def insert_worksheet(index = 0, options = {}) worksheet = Worksheet.new(self, options) @worksheets.delete_at(@worksheets.size - 1) @worksheets.insert(index, worksheet) @@ -320,7 +312,7 @@ require 'axlsx/workbook/worksheet/selection.rb' # @option options [String] name The name of the worksheet. # @option options [Hash] page_margins The page margins for the worksheet. # @see Worksheet#initialize - def add_worksheet(options={}) + def add_worksheet(options = {}) worksheet = Worksheet.new(self, options) yield worksheet if block_given? worksheet @@ -330,7 +322,7 @@ require 'axlsx/workbook/worksheet/selection.rb' # @return WorkbookViews # @option options [Hash] options passed into the added WorkbookView # @see WorkbookView#initialize - def add_view(options={}) + def add_view(options = {}) views << WorkbookView.new(options) end @@ -347,14 +339,14 @@ require 'axlsx/workbook/worksheet/selection.rb' def relationships r = Relationships.new @worksheets.each do |sheet| - r << Relationship.new(sheet, WORKSHEET_R, WORKSHEET_PN % (r.size+1)) + r << Relationship.new(sheet, WORKSHEET_R, WORKSHEET_PN % (r.size + 1)) end pivot_tables.each_with_index do |pivot_table, index| - r << Relationship.new(pivot_table.cache_definition, PIVOT_TABLE_CACHE_DEFINITION_R, PIVOT_TABLE_CACHE_DEFINITION_PN % (index+1)) + r << Relationship.new(pivot_table.cache_definition, PIVOT_TABLE_CACHE_DEFINITION_R, PIVOT_TABLE_CACHE_DEFINITION_PN % (index + 1)) end - r << Relationship.new(self, STYLES_R, STYLES_PN) + r << Relationship.new(self, STYLES_R, STYLES_PN) if use_shared_strings - r << Relationship.new(self, SHARED_STRINGS_R, SHARED_STRINGS_PN) + r << Relationship.new(self, SHARED_STRINGS_R, SHARED_STRINGS_PN) end r end @@ -391,13 +383,14 @@ require 'axlsx/workbook/worksheet/selection.rb' sheet_name = cell_def.split('!')[0] if cell_def.match('!') worksheet = self.worksheets.select { |s| s.name == sheet_name }.first raise ArgumentError, 'Unknown Sheet' unless sheet_name && worksheet.is_a?(Worksheet) - worksheet[cell_def.gsub(/.+!/,"")] + + worksheet[cell_def.gsub(/.+!/, "")] end # Serialize the workbook # @param [String] str # @return [String] - def to_xml_string(str='') + def to_xml_string(str = '') add_worksheet(name: 'Sheet1') unless worksheets.size > 0 str << '<?xml version="1.0" encoding="UTF-8"?>' str << ('<workbook xmlns="' << XML_NS << '" xmlns:r="' << XML_NS_R << '">') @@ -420,6 +413,5 @@ require 'axlsx/workbook/worksheet/selection.rb' end str << '</workbook>' end - end end diff --git a/lib/axlsx/workbook/workbook_view.rb b/lib/axlsx/workbook/workbook_view.rb index e0d38cae..27a46dcc 100644 --- a/lib/axlsx/workbook/workbook_view.rb +++ b/lib/axlsx/workbook/workbook_view.rb @@ -19,19 +19,16 @@ # </xsd:complexType> module Axlsx - # A BookView defines the display properties for a workbook. # Units for window widths and other dimensions are expressed in twips. # Twip measurements are portable between different display resolutions. # The formula is (screen pixels) * (20 * 72) / (logical device dpi), # where the logical device dpi can be different for x and y coordinates. class WorkbookView - include Axlsx::SerializedAttributes include Axlsx::OptionsParser include Axlsx::Accessors - # Creates a new BookView object # @param [Hash] options A hash of key/value pairs that will be mapped to this instances attributes. # @option [Symbol] visibility Specifies visible state of the workbook window. The default value for this attribute is :visible. @@ -47,16 +44,15 @@ module Axlsx # @option [Integer] window_width Specifies the width of the workbook window. The unit of measurement for this value is twips. # @option [Integer] window_height Specifies the height of the workbook window. The unit of measurement for this value is twips. # @option [Boolean] auto_filter_date_grouping Specifies a boolean value that indicates whether to group dates when presenting the user with filtering options in the user interface. - def initialize(options={}) + def initialize(options = {}) parse_options options yield self if block_given? end - unsigned_int_attr_accessor :x_window, :y_window, :window_width, :window_height, :tab_ratio, :first_sheet, :active_tab - validated_attr_accessor [:visibility], :validate_view_visibility + validated_attr_accessor [:visibility], :validate_view_visibility serializable_attributes :visibility, :minimized, :show_horizontal_scroll, :show_vertical_scroll, @@ -67,14 +63,13 @@ module Axlsx boolean_attr_accessor :minimized, :show_horizontal_scroll, :show_vertical_scroll, :show_sheet_tabs, :auto_filter_date_grouping - # Serialize the WorkbookView # @param [String] str # @return [String] def to_xml_string(str = '') - str << '<workbookView ' - serialized_attributes str - str << '></workbookView>' + str << '<workbookView ' + serialized_attributes str + str << '></workbookView>' end end end diff --git a/lib/axlsx/workbook/workbook_views.rb b/lib/axlsx/workbook/workbook_views.rb index c32bd632..41010d0d 100644 --- a/lib/axlsx/workbook/workbook_views.rb +++ b/lib/axlsx/workbook/workbook_views.rb @@ -1,7 +1,6 @@ module Axlsx # a simple types list of BookView objects class WorkbookViews < SimpleTypedList - # creates the book views object def initialize super WorkbookView @@ -12,11 +11,10 @@ module Axlsx # @return [String] def to_xml_string(str = '') return if empty? + str << "<bookViews>" each { |view| view.to_xml_string(str) } str << '</bookViews>' end end end - - diff --git a/lib/axlsx/workbook/worksheet/auto_filter/auto_filter.rb b/lib/axlsx/workbook/worksheet/auto_filter/auto_filter.rb index 9fd6be18..bf3426b6 100644 --- a/lib/axlsx/workbook/worksheet/auto_filter/auto_filter.rb +++ b/lib/axlsx/workbook/worksheet/auto_filter/auto_filter.rb @@ -1,16 +1,14 @@ - require 'axlsx/workbook/worksheet/auto_filter/filter_column.rb' require 'axlsx/workbook/worksheet/auto_filter/filters.rb' module Axlsx - - #This class represents an auto filter range in a worksheet + # This class represents an auto filter range in a worksheet class AutoFilter - # creates a new Autofilter object # @param [Worksheet] worksheet def initialize(worksheet) raise ArgumentError, 'you must provide a worksheet' unless worksheet.is_a?(Worksheet) + @worksheet = worksheet end @@ -27,7 +25,8 @@ module Axlsx # @return [String] def defined_name return unless range - Axlsx.cell_range(range.split(':').collect { |name| worksheet.name_to_cell(name)}) + + Axlsx.cell_range(range.split(':').collect { |name| worksheet.name_to_cell(name) }) end # A collection of filterColumns for this auto_filter @@ -54,24 +53,26 @@ module Axlsx start_point = Axlsx::name_to_indices(first_cell) end_point = Axlsx::name_to_indices(last_cell) # The +1 is so we skip the header row with the filter drop downs - rows = worksheet.rows[(start_point.last+1)..end_point.last] || [] + rows = worksheet.rows[(start_point.last + 1)..end_point.last] || [] column_offset = start_point.first columns.each do |column| rows.each do |row| next if row.hidden + column.apply(row, column_offset) end end end + # serialize the object # @return [String] - def to_xml_string(str='') + def to_xml_string(str = '') return unless range + str << "<autoFilter ref='#{range}'>" columns.each { |filter_column| filter_column.to_xml_string(str) } str << "</autoFilter>" end - end end diff --git a/lib/axlsx/workbook/worksheet/auto_filter/filter_column.rb b/lib/axlsx/workbook/worksheet/auto_filter/filter_column.rb index 71f08a2f..32a9df26 100644 --- a/lib/axlsx/workbook/worksheet/auto_filter/filter_column.rb +++ b/lib/axlsx/workbook/worksheet/auto_filter/filter_column.rb @@ -4,7 +4,6 @@ module Axlsx # If a column in the AutoFilter range has no criteria specified, # then there is no corresponding filterColumn collection expressed for that column. class FilterColumn - include Axlsx::OptionsParser include Axlsx::SerializedAttributes @@ -17,7 +16,7 @@ module Axlsx # @option [Boolean] show_button @see show_button def initialize(col_id, filter_type, options = {}) RestrictionValidator.validate 'FilterColumn.filter', FILTERS, filter_type - #Axlsx::validate_unsigned_int(col_id) + # Axlsx::validate_unsigned_int(col_id) self.col_id = col_id parse_options options @filter = Axlsx.const_get(Axlsx.camel(filter_type)).new(options) @@ -27,7 +26,7 @@ module Axlsx serializable_attributes :col_id, :hidden_button, :show_button # Allowed filters - FILTERS = [:filters] #, :top10, :custom_filters, :dynamic_filters, :color_filters, :icon_filters] + FILTERS = [:filters] # , :top10, :custom_filters, :dynamic_filters, :color_filters, :icon_filters] # Zero-based index indicating the AutoFilter column to which this filter information applies. # @return [Integer] @@ -52,7 +51,7 @@ module Axlsx end # Sets the col_id attribute for this filter column. - # @param [Integer | Cell] column_index The zero based index of the column to which this filter applies. + # @param [Integer | Cell] column_index The zero based index of the column to which this filter applies. # When you specify a cell, the column index will be read off the cell # @return [Integer] def col_id=(column_index) @@ -65,8 +64,9 @@ module Axlsx # @param [Array] row A row from a worksheet that needs to be # filtered. def apply(row, offset) - row.hidden = @filter.apply(row.cells[offset+col_id.to_i]) + row.hidden = @filter.apply(row.cells[offset + col_id.to_i]) end + # @param [Boolean] hidden Flag indicating whether the AutoFilter button for this column is hidden. # @return [Boolean] def hidden_button=(hidden) @@ -85,7 +85,7 @@ module Axlsx end # Serialize the object to xml - def to_xml_string(str='') + def to_xml_string(str = '') str << "<filterColumn #{serialized_attributes}>" @filter.to_xml_string(str) str << "</filterColumn>" diff --git a/lib/axlsx/workbook/worksheet/auto_filter/filters.rb b/lib/axlsx/workbook/worksheet/auto_filter/filters.rb index faa22374..83da2da2 100644 --- a/lib/axlsx/workbook/worksheet/auto_filter/filters.rb +++ b/lib/axlsx/workbook/worksheet/auto_filter/filters.rb @@ -1,6 +1,5 @@ module Axlsx - - # When multiple values are chosen to filter by, or when a group of date values are chosen to filter by, + # When multiple values are chosen to filter by, or when a group of date values are chosen to filter by, # this object groups those criteria together. class Filters include Axlsx::OptionsParser @@ -16,7 +15,7 @@ module Axlsx # @note The recommended way to interact with filter objects is via AutoFilter#add_column # @example # ws.auto_filter.add_column(0, :filters, :blank => true, :calendar_type => 'japan', :filter_items => [100, 'a']) - def initialize(options={}) + def initialize(options = {}) parse_options options end @@ -29,7 +28,7 @@ module Axlsx # @return [Boolean] attr_reader :blank - # Calendar type for date grouped items. + # Calendar type for date grouped items. # Used to interpret the values in dateGroupItem. # This is the calendar type used to evaluate all dates in the filter column, # even when those dates are not using the same calendar system / date formatting. @@ -42,6 +41,7 @@ module Axlsx # TODO implement this for date filters as well! def apply(cell) return false unless cell + filter_items.each do |filter| return false if cell.value == filter.val end @@ -76,12 +76,12 @@ module Axlsx # Serialize the object to xml def to_xml_string(str = '') str << "<filters #{serialized_attributes}>" - filter_items.each { |filter| filter.to_xml_string(str) } + filter_items.each { |filter| filter.to_xml_string(str) } date_group_items.each { |date_group_item| date_group_item.to_xml_string(str) } str << '</filters>' end - # not entirely happy with this. + # not entirely happy with this. # filter_items should be a simple typed list that overrides << etc # to create Filter objects from the inserted values. However this # is most likely so rarely used...(really? do you know that?) @@ -98,13 +98,13 @@ module Axlsx def date_group_items=(options) options.each do |date_group| raise ArgumentError, "date_group_items should be an array of hashes specifying the options for each date_group_item" unless date_group.is_a?(Hash) + date_group_items << DateGroupItem.new(date_group) end end # This class expresses a filter criteria value. class Filter - # Creates a new filter value object # @param [Any] value The value of the filter. This is not restricted, but # will be serialized via to_s so if you are passing an object @@ -113,8 +113,7 @@ module Axlsx @val = value end - - #Filter value used in the criteria. + # Filter value used in the criteria. attr_accessor :val # Serializes the filter value object @@ -124,7 +123,6 @@ module Axlsx end end - # This collection is used to express a group of dates or times which are # used in an AutoFilter criteria. Values are always written in the calendar # type of the first date encountered in the filter range, so that all @@ -132,7 +130,7 @@ module Axlsx # types, can be correctly compared for the purposes of filtering. class DateGroupItem include Axlsx::OptionsParser -include Axlsx::SerializedAttributes + include Axlsx::SerializedAttributes # Creates a new DateGroupItem # @param [Hash] options A hash of options to use when @@ -145,9 +143,10 @@ include Axlsx::SerializedAttributes # @option [Integer] hour @see hour # @option [Integer] minute @see minute # @option [Integer] second @see second - def initialize(options={}) - raise ArgumentError, "You must specify a year for date time grouping" unless options[:year] + def initialize(options = {}) + raise ArgumentError, "You must specify a year for date time grouping" unless options[:year] raise ArgumentError, "You must specify a date_time_grouping when creating a DateGroupItem for auto filter" unless options[:date_time_grouping] + parse_options options end @@ -200,7 +199,7 @@ include Axlsx::SerializedAttributes end # The day value for the date group item - # This must be between 1 and 31 + # This must be between 1 and 31 # @note no attempt is made to ensure the date value is valid for any given month def day=(value) RangeValidator.validate "DateGroupItem.day", 0, 31, value diff --git a/lib/axlsx/workbook/worksheet/border_creator.rb b/lib/axlsx/workbook/worksheet/border_creator.rb index bbd30473..0e2fa87b 100644 --- a/lib/axlsx/workbook/worksheet/border_creator.rb +++ b/lib/axlsx/workbook/worksheet/border_creator.rb @@ -1,5 +1,3 @@ -# encoding: UTF-8 - module Axlsx class BorderCreator def initialize(worksheet:, cells:, edges: nil, style: nil, color: nil) @@ -13,9 +11,9 @@ module Axlsx if @edges == :all @edges = Axlsx::Border::EDGES elsif [email protected]_a?(Array) - raise ArgumentError.new("Invalid edges provided, #{@edges}") + raise ArgumentError.new("Invalid edges provided, #{@edges}") else - @edges = @edges.map{|x| x&.to_sym}.uniq + @edges = @edges.map { |x| x&.to_sym }.uniq if !(@edges - Axlsx::Border::EDGES).empty? raise ArgumentError.new("Invalid edges provided, #{edges}") @@ -26,17 +24,17 @@ module Axlsx def draw if @cells.size == 1 @worksheet.add_style( - first_cell, + first_cell, { - border: {style: @style, color: @color, edges: @edges} + border: { style: @style, color: @color, edges: @edges } } ) else - @edges.each do |edge| + @edges.each do |edge| @worksheet.add_style( - border_cells[edge], + border_cells[edge], { - border: {style: @style, color: @color, edges: [edge]} + border: { style: @style, color: @color, edges: [edge] } } ) end @@ -50,7 +48,7 @@ module Axlsx top: "#{first_cell}:#{last_col}#{first_row}", right: "#{last_col}#{first_row}:#{last_cell}", bottom: "#{first_col}#{last_row}:#{last_cell}", - left: "#{first_cell}:#{first_col}#{last_row}", + left: "#{first_cell}:#{first_col}#{last_row}" } end @@ -77,6 +75,5 @@ module Axlsx def last_col @last_col ||= last_cell.scan(/\D+/).first end - end end diff --git a/lib/axlsx/workbook/worksheet/break.rb b/lib/axlsx/workbook/worksheet/break.rb index 2e40a265..f8cc452e 100644 --- a/lib/axlsx/workbook/worksheet/break.rb +++ b/lib/axlsx/workbook/worksheet/break.rb @@ -1,9 +1,7 @@ module Axlsx - # The Break class stores the details for row and column page breaks. # @see RowBreaks, ColBreaks class Break - include Axlsx::OptionsParser include Axlsx::Accessors include Axlsx::SerializedAttributes @@ -15,7 +13,7 @@ module Axlsx # @option options [Integer] max Zero-based index of end row or column of the break. For row breaks, specifies column index; for column breaks, specifies row index. # @option options [Boolean] man Manual Break flag. 1 means the break is a manually inserted break. # @option option [Boolean] pt Flag indicating that a PivotTable created this break. - def initialize(options={}) + def initialize(options = {}) parse_options options yield self if block_given? end @@ -27,9 +25,8 @@ module Axlsx serializable_attributes :id, :min, :max, :man, :pt # serializes the break to xml - def to_xml_string(str='') + def to_xml_string(str = '') serialized_tag('brk', str) end end end - diff --git a/lib/axlsx/workbook/worksheet/cell.rb b/lib/axlsx/workbook/worksheet/cell.rb index 125ca051..364de1e9 100644 --- a/lib/axlsx/workbook/worksheet/cell.rb +++ b/lib/axlsx/workbook/worksheet/cell.rb @@ -1,4 +1,3 @@ -# encoding: UTF-8 require 'cgi' module Axlsx # A cell in a worksheet. @@ -7,7 +6,6 @@ module Axlsx # # @see Worksheet#add_row class Cell - include Axlsx::OptionsParser # @param [Row] row The row this cell belongs to. @@ -104,7 +102,7 @@ module Axlsx self.raw_style = new_style wb = row.worksheet.workbook - + wb.styled_cells << self end @@ -152,7 +150,7 @@ module Axlsx # @see value def value=(v) - #TODO: consider doing value based type determination first? + # TODO: consider doing value based type determination first? @value = cast_value(v) end @@ -178,6 +176,7 @@ module Axlsx # The inline font_name property for the cell # @return [String] attr_reader :font_name + # @see font_name def font_name=(v) set_run_style :validate_string, :font_name, v; end @@ -204,6 +203,7 @@ module Axlsx # 255  OEM_CHARSET # @return [String] attr_reader :charset + # @see charset def charset=(v) set_run_style :validate_unsigned_int, :charset, v; end @@ -215,6 +215,7 @@ module Axlsx # 4 Script # 5 Decorative attr_reader :family + # @see family def family=(v) set_run_style :validate_family, :family, v.to_i @@ -223,42 +224,49 @@ module Axlsx # The inline bold property for the cell # @return [Boolean] attr_reader :b + # @see b def b=(v) set_run_style :validate_boolean, :b, v; end # The inline italic property for the cell # @return [Boolean] attr_reader :i + # @see i def i=(v) set_run_style :validate_boolean, :i, v; end # The inline strike property for the cell # @return [Boolean] attr_reader :strike + # @see strike def strike=(v) set_run_style :validate_boolean, :strike, v; end # The inline outline property for the cell # @return [Boolean] attr_reader :outline + # @see outline def outline=(v) set_run_style :validate_boolean, :outline, v; end # The inline shadow property for the cell # @return [Boolean] attr_reader :shadow + # @see shadow def shadow=(v) set_run_style :validate_boolean, :shadow, v; end # The inline condense property for the cell # @return [Boolean] attr_reader :condense + # @see condense def condense=(v) set_run_style :validate_boolean, :condense, v; end # The inline extend property for the cell # @return [Boolean] attr_reader :extend + # @see extend def extend=(v) set_run_style :validate_boolean, :extend, v; end @@ -268,6 +276,7 @@ module Axlsx # @return [String] # @note true is for backwards compatability and is reassigned to :single attr_reader :u + # @see u def u=(v) v = :single if (v == true || v == 1 || v == :true || v == 'true') @@ -277,15 +286,17 @@ module Axlsx # The inline color property for the cell # @return [Color] attr_reader :color + # @param [String] v The 8 character representation for an rgb color #FFFFFFFF" def color=(v) - @color = v.is_a?(Color) ? v : Color.new(:rgb=>v) + @color = v.is_a?(Color) ? v : Color.new(:rgb => v) @is_text_run = true end # The inline sz property for the cell # @return [Inteter] attr_reader :sz + # @see sz def sz=(v) set_run_style :validate_unsigned_int, :sz, v; end @@ -293,6 +304,7 @@ module Axlsx # this must be one of [:baseline, :subscript, :superscript] # @return [Symbol] attr_reader :vertAlign + # @see vertAlign def vertAlign=(v) RestrictionValidator.validate :cell_vertAlign, [:baseline, :subscript, :superscript], v @@ -303,6 +315,7 @@ module Axlsx # this must be one of [:none, major, minor] # @return [Symbol] attr_reader :scheme + # @see scheme def scheme=(v) RestrictionValidator.validate :cell_scheme, [:none, :major, :minor], v @@ -329,7 +342,7 @@ module Axlsx # @example Absolute Cell Reference # ws.rows.first.cells.first.r #=> "$A$1" def r_abs - "$#{r.match(%r{([A-Z]+)([0-9]+)})[1,2].join('$')}" + "$#{r.match(%r{([A-Z]+)([0-9]+)})[1, 2].join('$')}" end # @return [Integer] The cellXfs item index applied to this cell. @@ -338,6 +351,7 @@ module Axlsx Axlsx::validate_unsigned_int(v) count = styles.cellXfs.size raise ArgumentError, "Invalid cellXfs id" unless v < count + @style = v end @@ -352,7 +366,7 @@ module Axlsx def merge(target) start, stop = if target.is_a?(String) [self.r, target] - elsif(target.is_a?(Cell)) + elsif target.is_a?(Cell) Axlsx.sort_cells([self, target]).map { |c| c.r } end self.row.worksheet.merge_cells "#{start}:#{stop}" unless stop.nil? @@ -382,7 +396,7 @@ module Axlsx # @param [Boolean] absolute -when false a relative reference will be # returned. # @return [String] - def reference(absolute=true) + def reference(absolute = true) absolute ? r_abs : r end @@ -452,6 +466,7 @@ module Axlsx # Utility method for setting inline style attributes def set_run_style(validator, attr, value) return unless INLINE_STYLES.include?(attr.to_sym) + Axlsx.send(validator, value) unless validator.nil? self.instance_variable_set :"@#{attr.to_s}", value @is_text_run = true @@ -499,6 +514,7 @@ module Axlsx # @see Axlsx#date1904 def cast_value(v) return v if v.is_a?(RichText) || v.nil? + case type when :date self.style = STYLE_DATE if self.style == 0 @@ -521,12 +537,11 @@ module Axlsx when :boolean v ? 1 : 0 when :iso_8601 - #consumer is responsible for ensuring the iso_8601 format when specifying this type + # consumer is responsible for ensuring the iso_8601 format when specifying this type v else v.to_s end end - end end diff --git a/lib/axlsx/workbook/worksheet/cell_serializer.rb b/lib/axlsx/workbook/worksheet/cell_serializer.rb index 962b575d..94a1f93a 100644 --- a/lib/axlsx/workbook/worksheet/cell_serializer.rb +++ b/lib/axlsx/workbook/worksheet/cell_serializer.rb @@ -1,5 +1,4 @@ module Axlsx - # The Cell Serializer class contains the logic for serializing cells based on their type. class CellSerializer class << self @@ -8,9 +7,10 @@ module Axlsx # @param [Integer] column_index The index of the cell's column # @param [String] str The string to apend serialization to. # @return [String] - def to_xml_string(row_index, column_index, cell, str='') + def to_xml_string(row_index, column_index, cell, str = '') str << ('<c r="' << Axlsx::cell_r(column_index, row_index) << '" s="' << cell.style.to_s << '" ') return str << '/>' if cell.value.nil? + method = cell.type self.send(method, cell, str) str << '</c>' @@ -22,7 +22,7 @@ module Axlsx def run_xml_string(cell, str = '') if cell.is_text_run? valid = RichTextRun::INLINE_STYLES - [:value, :type] - data = Hash[Axlsx.instance_values_for(cell).map{ |k, v| [k.to_sym, v] }] + data = Hash[Axlsx.instance_values_for(cell).map { |k, v| [k.to_sym, v] }] data = data.select { |key, value| valid.include?(key) && !value.nil? } RichText.new(cell.value.to_s, data).to_xml_string(str) elsif cell.contains_rich_text? @@ -37,7 +37,7 @@ module Axlsx # @param [Cell] cell The cell that is being serialized # @param [String] str The string the serialized content will be appended to. # @return [String] - def iso_8601(cell, str='') + def iso_8601(cell, str = '') value_serialization 'd', cell.value, str end @@ -45,7 +45,7 @@ module Axlsx # @param [Cell] cell The cell that is being serialized # @param [String] str The string the serialized content will be appended to. # @return [String] - def date(cell, str='') + def date(cell, str = '') value_serialization false, DateTimeConverter::date_to_serial(cell.value).to_s, str end @@ -53,7 +53,7 @@ module Axlsx # @param [Cell] cell The cell that is being serialized # @param [String] str The string the serialized content will be appended to. # @return [String] - def time(cell, str='') + def time(cell, str = '') value_serialization false, DateTimeConverter::time_to_serial(cell.value).to_s, str end @@ -61,7 +61,7 @@ module Axlsx # @param [Cell] cell The cell that is being serialized # @param [String] str The string the serialized content will be appended to. # @return [String] - def boolean(cell, str='') + def boolean(cell, str = '') value_serialization 'b', cell.value.to_s, str end @@ -69,7 +69,7 @@ module Axlsx # @param [Cell] cell The cell that is being serialized # @param [String] str The string the serialized content will be appended to. # @return [String] - def float(cell, str='') + def float(cell, str = '') numeric cell, str end @@ -85,7 +85,7 @@ module Axlsx # @param [Cell] cell The cell that is being serialized # @param [String] str The string the serialized content will be appended to. # @return [String] - def formula_serialization(cell, str='') + def formula_serialization(cell, str = '') str << ('t="str"><f>' << cell.clean_value.to_s.sub('=', '') << '</f>') str << ('<v>' << cell.formula_value.to_s << '</v>') unless cell.formula_value.nil? end @@ -94,7 +94,7 @@ module Axlsx # @param [Cell] cell The cell that is being serialized # @param [String] str The string the serialized content will be appended to. # @return [String] - def array_formula_serialization(cell, str='') + def array_formula_serialization(cell, str = '') str << ('t="str">' << '<f t="array" ref="' << cell.r << '">' << cell.clean_value.to_s.sub('{=', '').sub(/}$/, '') << '</f>') str << ('<v>' << cell.formula_value.to_s << '</v>') unless cell.formula_value.nil? end @@ -113,7 +113,7 @@ module Axlsx # @param [Cell] cell The cell that is being serialized # @param [String] str The string the serialized content will be appended to. # @return [String] - def string(cell, str='') + def string(cell, str = '') if cell.is_array_formula? array_formula_serialization cell, str elsif cell.is_formula? diff --git a/lib/axlsx/workbook/worksheet/cfvo.rb b/lib/axlsx/workbook/worksheet/cfvo.rb index c2a4c781..faa5d88a 100644 --- a/lib/axlsx/workbook/worksheet/cfvo.rb +++ b/lib/axlsx/workbook/worksheet/cfvo.rb @@ -7,7 +7,6 @@ module Axlsx # @see ConditionalFormattingRule#initialize # class Cfvo - include Axlsx::OptionsParser include Axlsx::SerializedAttributes @@ -15,7 +14,7 @@ module Axlsx # @option options [Symbol] type The type of conditional formatting value object # @option options [Boolean] gte threshold value usage indicator # @option options [String] val The value of the conditional formatting object - def initialize(options={}) + def initialize(options = {}) @gte = true parse_options options end @@ -47,6 +46,7 @@ module Axlsx # @see val def val=(v) raise ArgumentError, "#{v.inspect} must respond to to_s" unless v.respond_to?(:to_s) + @val = v.to_s end diff --git a/lib/axlsx/workbook/worksheet/cfvos.rb b/lib/axlsx/workbook/worksheet/cfvos.rb index eb44f9d8..c5fa80f3 100644 --- a/lib/axlsx/workbook/worksheet/cfvos.rb +++ b/lib/axlsx/workbook/worksheet/cfvos.rb @@ -1,9 +1,7 @@ module Axlsx - - #A collection of Cfvo objects that initializes with the required - #first two items + # A collection of Cfvo objects that initializes with the required + # first two items class Cfvos < SimpleTypedList - def initialize super(Cfvo) end @@ -11,7 +9,7 @@ module Axlsx # Serialize the Cfvo object # @param [String] str # @return [String] - def to_xml_string(str='') + def to_xml_string(str = '') each { |cfvo| cfvo.to_xml_string(str) } end end diff --git a/lib/axlsx/workbook/worksheet/col.rb b/lib/axlsx/workbook/worksheet/col.rb index 3b3775c4..37c38365 100644 --- a/lib/axlsx/workbook/worksheet/col.rb +++ b/lib/axlsx/workbook/worksheet/col.rb @@ -1,9 +1,6 @@ -# encoding: UTF-8 module Axlsx - # The Col class defines column attributes for columns in sheets. class Col - # Maximum column width limit in MS Excel is 255 characters # https://support.microsoft.com/en-us/office/excel-specifications-and-limits-1672b34d-7043-467e-8e27-269d656771c3 MAX_WIDTH = 255 @@ -19,7 +16,7 @@ module Axlsx # @option options [Boolean] phonetic see Col#phonetic # @option options [Integer] style see Col#style # @option options [Numeric] width see Col#width - def initialize(min, max, options={}) + def initialize(min, max, options = {}) Axlsx.validate_unsigned_int(max) Axlsx.validate_unsigned_int(min) @min = min @@ -90,6 +87,7 @@ module Axlsx def outline_level=(v) Axlsx.validate_unsigned_numeric(v) raise ArgumentError, 'outlineLevel must be between 0 and 7' unless 0 <= v && v <= 7 + @outline_level = v end alias :outlineLevel= :outline_level= @@ -106,14 +104,14 @@ module Axlsx @style = v end - # @see Col#width + # @see Col#width def width=(v) # Removing this validation make a 10% difference in performance # as it is called EVERY TIME A CELL IS ADDED - the proper solution # is to only set this if a calculated value is greated than the # current @width value. # TODO!!! - #Axlsx.validate_unsigned_numeric(v) unless v == nil + # Axlsx.validate_unsigned_numeric(v) unless v == nil @custom_width = @best_fit = v != nil @width = v.nil? ? v : [v, MAX_WIDTH].min end @@ -140,6 +138,5 @@ module Axlsx def to_xml_string(str = '') serialized_tag('col', str) end - end end diff --git a/lib/axlsx/workbook/worksheet/col_breaks.rb b/lib/axlsx/workbook/worksheet/col_breaks.rb index 2f1ec1b0..78ccc565 100644 --- a/lib/axlsx/workbook/worksheet/col_breaks.rb +++ b/lib/axlsx/workbook/worksheet/col_breaks.rb @@ -1,10 +1,8 @@ module Axlsx - # A collection of Brake objects. - # Please do not use this class directly. Instead use + # Please do not use this class directly. Instead use # Worksheet#add_break class ColBreaks < SimpleTypedList - # Instantiates a new list restricted to Break types def initialize super Break @@ -12,7 +10,7 @@ module Axlsx # A column break specific helper for adding a break. # @param [Hash] options A list of options to pass into the Break object - # The max and man options are fixed, however any other valid option for + # The max and man options are fixed, however any other valid option for # Break will be passed to the created break object. # @see Break def add_break(options) @@ -25,8 +23,9 @@ module Axlsx # <colBreaks count="1" manualBreakCount="1"> # <brk id="3" max="1048575" man="1"/> # </colBreaks> - def to_xml_string(str='') + def to_xml_string(str = '') return if empty? + str << ('<colBreaks count="' << size.to_s << '" manualBreakCount="' << size.to_s << '">') each { |brk| brk.to_xml_string(str) } str << '</colBreaks>' diff --git a/lib/axlsx/workbook/worksheet/color_scale.rb b/lib/axlsx/workbook/worksheet/color_scale.rb index 287e6869..75877915 100644 --- a/lib/axlsx/workbook/worksheet/color_scale.rb +++ b/lib/axlsx/workbook/worksheet/color_scale.rb @@ -6,14 +6,12 @@ module Axlsx # @see Worksheet#add_conditional_formatting # @see ConditionalFormattingRule#initialize class ColorScale - class << self - # These are the default conditional formatting value objects # that define a two tone color gradient. def default_cfvos - [{:type => :min, :val => 0, :color => 'FFFF7128'}, - {:type => :max, :val => 0, :color => 'FFFFEF9C'}] + [{ :type => :min, :val => 0, :color => 'FFFF7128' }, + { :type => :max, :val => 0, :color => 'FFFFEF9C' }] end # A builder for two tone color gradient @@ -28,12 +26,12 @@ module Axlsx # A builder for three tone color gradient # @example # #this creates a three tone color scale - # color_scale = Axlsx::ColorScale.three_tone + # color_scale = Axlsx::ColorScale.three_tone # @see examples/example.rb conditional formatting examples. def three_tone - self.new({:type => :min, :val => 0, :color => 'FFF8696B'}, - {:type => :percent, :val => '50', :color => 'FFFFEB84'}, - {:type => :max, :val => 0, :color => 'FF63BE7B'}) + self.new({ :type => :min, :val => 0, :color => 'FFF8696B' }, + { :type => :percent, :val => '50', :color => 'FFFFEB84' }, + { :type => :max, :val => 0, :color => 'FF63BE7B' }) end end # A simple typed list of cfvos @@ -67,17 +65,16 @@ module Axlsx # @option [Symbol] type The type of cfvo you to add # @option [Any] val The value of the cfvo to add # @option [String] The rgb color for the cfvo - def add(options={}) + def add(options = {}) value_objects << Cfvo.new(:type => options[:type] || :min, :val => options[:val] || 0) colors << Color.new(:rgb => options[:color] || "FF000000") - {:cfvo => value_objects.last, :color => colors.last} + { :cfvo => value_objects.last, :color => colors.last } end - # removes the cfvo and color pair at the index specified. # @param [Integer] index The index of the cfvo and color object to delete # @note you cannot remove the first two cfvo and color pairs - def delete_at(index=2) + def delete_at(index = 2) value_objects.delete_at index colors.delete_at index end @@ -93,6 +90,7 @@ module Axlsx end private + # There has got to be cleaner way of merging these arrays. def initialize_default_cfvos(user_cfvos) defaults = self.class.default_cfvos diff --git a/lib/axlsx/workbook/worksheet/cols.rb b/lib/axlsx/workbook/worksheet/cols.rb index c0704343..27b1f508 100644 --- a/lib/axlsx/workbook/worksheet/cols.rb +++ b/lib/axlsx/workbook/worksheet/cols.rb @@ -1,11 +1,10 @@ module Axlsx - # The cols class manages the col object used to manage column widths. # This is where the magic happens with autowidth class Cols < SimpleTypedList - def initialize(worksheet) raise ArgumentError, "you must provide a worksheet" unless worksheet.is_a?(Worksheet) + super Col @worksheet = worksheet end @@ -14,10 +13,11 @@ module Axlsx # @param [String] str # @return [String] def to_xml_string(str = '') - return if empty? - str << '<cols>' - each { |item| item.to_xml_string(str) } - str << '</cols>' + return if empty? + + str << '<cols>' + each { |item| item.to_xml_string(str) } + str << '</cols>' end end end diff --git a/lib/axlsx/workbook/worksheet/comment.rb b/lib/axlsx/workbook/worksheet/comment.rb index e5dbe41c..aa35feef 100644 --- a/lib/axlsx/workbook/worksheet/comment.rb +++ b/lib/axlsx/workbook/worksheet/comment.rb @@ -1,8 +1,6 @@ module Axlsx - # A comment is the text data for a comment class Comment - include Axlsx::OptionsParser include Axlsx::Accessors @@ -13,8 +11,9 @@ module Axlsx # @option [String] text The text for the comment # @option [String] ref The refence (e.g. 'A3' where this comment will be anchored. # @option [Boolean] visible This controls the visiblity of the associated vml_shape. - def initialize(comments, options={}) + def initialize(comments, options = {}) raise ArgumentError, "A comment needs a parent comments object" unless comments.is_a?(Comments) + @visible = true @comments = comments parse_options options @@ -82,9 +81,9 @@ module Axlsx pos = Axlsx::name_to_indices(ref) @vml_shape = VmlShape.new(:row => pos[1], :column => pos[0], :visible => @visible) do |vml| vml.left_column = vml.column - vml.right_column = vml.column + 2 + vml.right_column = vml.column + 2 vml.top_row = vml.row - vml.bottom_row = vml.row + 4 + vml.bottom_row = vml.row + 4 end end end diff --git a/lib/axlsx/workbook/worksheet/comments.rb b/lib/axlsx/workbook/worksheet/comments.rb index dfc6d143..f6f3071b 100644 --- a/lib/axlsx/workbook/worksheet/comments.rb +++ b/lib/axlsx/workbook/worksheet/comments.rb @@ -1,9 +1,6 @@ -# -*- coding: utf-8 -*- module Axlsx - # Comments is a collection of Comment objects for a worksheet class Comments < SimpleTypedList - # the vml_drawing that holds the shapes for comments # @return [VmlDrawing] attr_reader :vml_drawing @@ -21,13 +18,14 @@ module Axlsx # The part name for this object # @return [String] def pn - "#{COMMENT_PN % (index+1)}" + "#{COMMENT_PN % (index + 1)}" end # Creates a new Comments object # @param [Worksheet] worksheet The sheet that these comments belong to. def initialize(worksheet) raise ArgumentError, "you must provide a worksheet" unless worksheet.is_a?(Worksheet) + super(Comment) @worksheet = worksheet @vml_drawing = VmlDrawing.new(self) @@ -38,10 +36,11 @@ module Axlsx # @option options [String] author The name of the author for this comment # @option options [String] text The text for this comment # @option options [Stirng|Cell] ref The cell that this comment is attached to. - def add_comment(options={}) + def add_comment(options = {}) raise ArgumentError, "Comment require an author" unless options[:author] raise ArgumentError, "Comment requires text" unless options[:text] raise ArgumentError, "Comment requires ref" unless options[:ref] + self << Comment.new(self, options) yield last if block_given? last @@ -63,10 +62,10 @@ module Axlsx # serialize the object # @param [String] str # @return [String] - def to_xml_string(str="") + def to_xml_string(str = "") str << '<?xml version="1.0" encoding="UTF-8"?>' str << ('<comments xmlns="' << XML_NS << '"><authors>') - authors.each do |author| + authors.each do |author| str << ('<author>' << author.to_s << '</author>') end str << '</authors><commentList>' @@ -74,9 +73,6 @@ module Axlsx comment.to_xml_string str end str << '</commentList></comments>' - end - end - end diff --git a/lib/axlsx/workbook/worksheet/conditional_formatting.rb b/lib/axlsx/workbook/worksheet/conditional_formatting.rb index 7b1783bd..419e6684 100644 --- a/lib/axlsx/workbook/worksheet/conditional_formatting.rb +++ b/lib/axlsx/workbook/worksheet/conditional_formatting.rb @@ -5,13 +5,12 @@ module Axlsx # @see Worksheet#add_conditional_formatting # @see ConditionalFormattingRule class ConditionalFormatting + include Axlsx::OptionsParser - include Axlsx::OptionsParser - # Creates a new {ConditionalFormatting} object # @option options [Array] rules The rules to apply # @option options [String] sqref The range to apply the rules to - def initialize(options={}) + def initialize(options = {}) @rules = [] parse_options options end @@ -28,7 +27,7 @@ module Axlsx # @return [Array] attr_reader :rules - # Add Conditional Formatting Rules to this object. Rules can either + # Add Conditional Formatting Rules to this object. Rules can either # be already created {ConditionalFormattingRule} elements or # hashes of options for automatic creation. If rules is a hash # instead of an array, assume only one rule being added. @@ -75,7 +74,7 @@ module Axlsx # @return [String] def to_xml_string(str = '') str << ('<conditionalFormatting sqref="' << sqref << '">') - str << rules.collect{ |rule| rule.to_xml_string }.join(' ') + str << rules.collect { |rule| rule.to_xml_string }.join(' ') str << '</conditionalFormatting>' end end diff --git a/lib/axlsx/workbook/worksheet/conditional_formatting_rule.rb b/lib/axlsx/workbook/worksheet/conditional_formatting_rule.rb index 13374bc4..4f84080b 100644 --- a/lib/axlsx/workbook/worksheet/conditional_formatting_rule.rb +++ b/lib/axlsx/workbook/worksheet/conditional_formatting_rule.rb @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- module Axlsx # Conditional formatting rules specify formulas whose evaluations # format cells @@ -7,7 +6,6 @@ module Axlsx # @see Worksheet#add_conditional_formatting # @see ConditionalFormattingRule#initialize class ConditionalFormattingRule - include Axlsx::OptionsParser include Axlsx::SerializedAttributes @@ -26,7 +24,7 @@ module Axlsx # @option options [Boolean] stopIfTrue Stop evaluating rules after this rule matches # @option options [Symbol] timePeriod The time period in a date occuring... rule # @option options [String] formula The formula to match against in i.e. an equal rule. Use a [minimum, maximum] array for cellIs between/notBetween conditionals. - def initialize(options={}) + def initialize(options = {}) @color_scale = @data_bar = @icon_set = @formula = nil parse_options options end @@ -133,7 +131,6 @@ module Axlsx # thisMonth, lastMonth, nextMonth, thisWeek, lastWeek, nextWeek attr_reader :timePeriod - # colorScale (Color Scale) # The color scale to apply to this conditional formatting # @return [ColorScale] @@ -182,7 +179,7 @@ module Axlsx # @see timePeriod def timePeriod=(v); Axlsx::validate_time_period_type(v); @timePeriod = v end # @see formula - def formula=(v); [*v].each {|x| Axlsx::validate_string(x) }; @formula = [*v].map { |form| ::CGI.escapeHTML(form) } end + def formula=(v); [*v].each { |x| Axlsx::validate_string(x) }; @formula = [*v].map { |form| ::CGI.escapeHTML(form) } end # @see color_scale def color_scale=(v) @@ -202,7 +199,6 @@ module Axlsx @icon_set = v end - # Serializes the conditional formatting rule # @param [String] str # @return [String] diff --git a/lib/axlsx/workbook/worksheet/conditional_formattings.rb b/lib/axlsx/workbook/worksheet/conditional_formattings.rb index 2fe9f2e8..8b510ab9 100644 --- a/lib/axlsx/workbook/worksheet/conditional_formattings.rb +++ b/lib/axlsx/workbook/worksheet/conditional_formattings.rb @@ -1,11 +1,10 @@ module Axlsx - # A simple, self serializing class for storing conditional formattings class ConditionalFormattings < SimpleTypedList - # creates a new Tables object def initialize(worksheet) raise ArgumentError, "you must provide a worksheet" unless worksheet.is_a?(Worksheet) + super ConditionalFormatting @worksheet = worksheet end @@ -17,9 +16,8 @@ module Axlsx # serialize the conditional formattings def to_xml_string(str = "") return if empty? + each { |item| item.to_xml_string(str) } end end - end - diff --git a/lib/axlsx/workbook/worksheet/data_bar.rb b/lib/axlsx/workbook/worksheet/data_bar.rb index e6455f1c..c9f99dcc 100644 --- a/lib/axlsx/workbook/worksheet/data_bar.rb +++ b/lib/axlsx/workbook/worksheet/data_bar.rb @@ -6,15 +6,14 @@ module Axlsx # @see Worksheet#add_conditional_formatting # @see ConditionalFormattingRule#initialize class DataBar - include Axlsx::OptionsParser include Axlsx::SerializedAttributes class << self # This differs from ColorScale. There must be exactly two cfvos one color def default_cfvos - [{:type => :min, :val => "0"}, - {:type => :max, :val => "0"}] + [{ :type => :min, :val => "0" }, + { :type => :max, :val => "0" }] end end @@ -81,32 +80,32 @@ module Axlsx end alias :minLength= :min_length= - # @see maxLength - def max_length=(v) - Axlsx.validate_unsigned_int(v) - @max_length = v - end + # @see maxLength + def max_length=(v) + Axlsx.validate_unsigned_int(v) + @max_length = v + end alias :maxLength= :max_length= - # @see showValue - def show_value=(v) - Axlsx.validate_boolean(v) - @show_value = v - end + # @see showValue + def show_value=(v) + Axlsx.validate_boolean(v) + @show_value = v + end alias :showValue= :show_value= - # Sets the color for the data bars. - # @param [Color|String] v The color object, or rgb string value to apply - def color=(v) - @color = v if v.is_a? Color - self.color.rgb = v if v.is_a? String - @color - end + # Sets the color for the data bars. + # @param [Color|String] v The color object, or rgb string value to apply + def color=(v) + @color = v if v.is_a? Color + self.color.rgb = v if v.is_a? String + @color + end # Serialize this object to an xml string # @param [String] str # @return [String] - def to_xml_string(str="") + def to_xml_string(str = "") serialized_tag('dataBar', str) do value_objects.to_xml_string(str) self.color.to_xml_string(str) @@ -124,6 +123,5 @@ module Axlsx end end end - end end diff --git a/lib/axlsx/workbook/worksheet/data_validation.rb b/lib/axlsx/workbook/worksheet/data_validation.rb index 71f9bbe6..741dee86 100644 --- a/lib/axlsx/workbook/worksheet/data_validation.rb +++ b/lib/axlsx/workbook/worksheet/data_validation.rb @@ -1,4 +1,3 @@ -# encoding: UTF-8 module Axlsx # Data validation allows the validation of cell data # @@ -23,7 +22,7 @@ module Axlsx # @option options [Boolean] showInputMessage - A boolean value indicating whether to display the input prompt message. # @option options [String] sqref - Range over which data validation is applied, in "A1:B2" format. # @option options [Symbol] type - The type of data validation. - def initialize(options={}) + def initialize(options = {}) # defaults @formula1 = @formula2 = @error = @errorTitle = @operator = @prompt = @promptTitle = @sqref = nil @allowBlank = @showErrorMessage = true @@ -176,7 +175,6 @@ module Axlsx # default none attr_reader :type - # @see formula1 def formula1=(v); Axlsx::validate_string(v); @formula1 = v end @@ -246,9 +244,10 @@ module Axlsx str << '</dataValidation>' end - private + private + def get_valid_attributes - attributes = [:allowBlank, :error, :errorStyle, :errorTitle, :prompt, :promptTitle, :showErrorMessage, :showInputMessage, :sqref, :type ] + attributes = [:allowBlank, :error, :errorStyle, :errorTitle, :prompt, :promptTitle, :showErrorMessage, :showInputMessage, :sqref, :type] if [:whole, :decimal, :data, :time, :date, :textLength].include?(@type) attributes << [:operator, :formula1] diff --git a/lib/axlsx/workbook/worksheet/data_validations.rb b/lib/axlsx/workbook/worksheet/data_validations.rb index cdfcf375..9c07da42 100644 --- a/lib/axlsx/workbook/worksheet/data_validations.rb +++ b/lib/axlsx/workbook/worksheet/data_validations.rb @@ -1,11 +1,10 @@ module Axlsx - # A simple, self serializing class for storing conditional formattings class DataValidations < SimpleTypedList - # creates a new Tables object def initialize(worksheet) raise ArgumentError, "you must provide a worksheet" unless worksheet.is_a?(Worksheet) + super DataValidation @worksheet = worksheet end @@ -17,12 +16,10 @@ module Axlsx # serialize the conditional formattings def to_xml_string(str = "") return if empty? + str << "<dataValidations count='#{size}'>" each { |item| item.to_xml_string(str) } str << '</dataValidations>' end end - end - - diff --git a/lib/axlsx/workbook/worksheet/date_time_converter.rb b/lib/axlsx/workbook/worksheet/date_time_converter.rb index 44f9fec4..ff85c64f 100644 --- a/lib/axlsx/workbook/worksheet/date_time_converter.rb +++ b/lib/axlsx/workbook/worksheet/date_time_converter.rb @@ -1,10 +1,8 @@ -# encoding: UTF-8 require "date" module Axlsx # The DateTimeConverter class converts both data and time types to their apprpriate excel serializations class DateTimeConverter - # The date_to_serial method converts Date objects to the equivelant excel serialized forms # @param [Date] date the date to be serialized # @return [Numeric] @@ -24,7 +22,7 @@ module Axlsx epoch1904 = -2082844800.0 # Time.utc(1904, 1, 1).to_i seconds_per_day = 86400.0 # 60*60*24 epoch = Axlsx::Workbook::date1904 ? epoch1904 : epoch1900 - (time.utc_offset + time.to_f - epoch)/seconds_per_day + (time.utc_offset + time.to_f - epoch) / seconds_per_day end end end diff --git a/lib/axlsx/workbook/worksheet/dimension.rb b/lib/axlsx/workbook/worksheet/dimension.rb index a7f9b792..013097c8 100644 --- a/lib/axlsx/workbook/worksheet/dimension.rb +++ b/lib/axlsx/workbook/worksheet/dimension.rb @@ -1,10 +1,8 @@ module Axlsx - # This class manages the dimensions for a worksheet. - # While this node is optional in the specification some readers like + # While this node is optional in the specification some readers like # LibraOffice require this node to render the sheet class Dimension - # the default value for the first cell in the dimension # @return [String] def self.default_first @@ -22,6 +20,7 @@ module Axlsx # to. def initialize(worksheet) raise ArgumentError, "you must provide a worksheet" unless worksheet.is_a?(Worksheet) + @worksheet = worksheet end @@ -31,12 +30,13 @@ module Axlsx # @return [String] def sqref "#{first_cell_reference}:#{last_cell_reference}" - end + end # serialize the object # @return [String] def to_xml_string(str = '') return if worksheet.rows.empty? + str << "<dimension ref=\"%s\"></dimension>" % sqref end @@ -58,6 +58,7 @@ module Axlsx # @return [String] def dimension_reference(cell, default) return default unless cell.respond_to?(:r) + cell.r end end diff --git a/lib/axlsx/workbook/worksheet/header_footer.rb b/lib/axlsx/workbook/worksheet/header_footer.rb index db684fc9..5ad00565 100644 --- a/lib/axlsx/workbook/worksheet/header_footer.rb +++ b/lib/axlsx/workbook/worksheet/header_footer.rb @@ -9,7 +9,6 @@ module Axlsx # @note The recommended way of managing header/footers is via Worksheet#header_footer # @see Worksheet#initialize class HeaderFooter - include Axlsx::OptionsParser include Axlsx::SerializedAttributes include Axlsx::Accessors diff --git a/lib/axlsx/workbook/worksheet/icon_set.rb b/lib/axlsx/workbook/worksheet/icon_set.rb index 400a8c47..4e7064e9 100644 --- a/lib/axlsx/workbook/worksheet/icon_set.rb +++ b/lib/axlsx/workbook/worksheet/icon_set.rb @@ -6,7 +6,6 @@ module Axlsx # @see Worksheet#add_conditional_formatting # @see ConditionalFormattingRule#initialize class IconSet - include Axlsx::OptionsParser include Axlsx::SerializedAttributes @@ -47,7 +46,7 @@ module Axlsx # @return [Boolean] attr_reader :showValue - # @see iconSet + # @see iconSet def iconSet=(v); Axlsx::validate_icon_set(v); @iconSet = v end # @see showValue @@ -62,7 +61,7 @@ module Axlsx # Serialize this object to an xml string # @param [String] str # @return [String] - def to_xml_string(str="") + def to_xml_string(str = "") serialized_tag('iconSet', str) do @value_objects.each { |cfvo| cfvo.to_xml_string(str) } end diff --git a/lib/axlsx/workbook/worksheet/merged_cells.rb b/lib/axlsx/workbook/worksheet/merged_cells.rb index 67753bd3..f54fd252 100644 --- a/lib/axlsx/workbook/worksheet/merged_cells.rb +++ b/lib/axlsx/workbook/worksheet/merged_cells.rb @@ -1,12 +1,11 @@ module Axlsx - # A simple list of merged cells class MergedCells < SimpleTypedList - # creates a new MergedCells object # @param [Worksheet] worksheet def initialize(worksheet) raise ArgumentError, 'you must provide a worksheet' unless worksheet.is_a?(Worksheet) + super String end @@ -16,12 +15,12 @@ module Axlsx # range like 'A1:C1' def add(cells) self << if cells.is_a?(String) - cells - elsif cells.is_a?(Array) - Axlsx::cell_range(cells, false) - elsif cells.is_a?(Row) - Axlsx::cell_range(cells, false) - end + cells + elsif cells.is_a?(Array) + Axlsx::cell_range(cells, false) + elsif cells.is_a?(Row) + Axlsx::cell_range(cells, false) + end end # serialize the object @@ -29,6 +28,7 @@ module Axlsx # @return [String] def to_xml_string(str = '') return if empty? + str << "<mergeCells count='#{size}'>" each { |merged_cell| str << "<mergeCell ref='#{merged_cell}'></mergeCell>" } str << '</mergeCells>' diff --git a/lib/axlsx/workbook/worksheet/outline_pr.rb b/lib/axlsx/workbook/worksheet/outline_pr.rb index f25ef4fa..5db0d825 100644 --- a/lib/axlsx/workbook/worksheet/outline_pr.rb +++ b/lib/axlsx/workbook/worksheet/outline_pr.rb @@ -1,5 +1,4 @@ module Axlsx - # The OutlinePr class manages serialization of a worksheet's outlinePr element, which provides various # options to control outlining. class OutlinePr diff --git a/lib/axlsx/workbook/worksheet/page_margins.rb b/lib/axlsx/workbook/worksheet/page_margins.rb index b3f8ddee..a0967817 100644 --- a/lib/axlsx/workbook/worksheet/page_margins.rb +++ b/lib/axlsx/workbook/worksheet/page_margins.rb @@ -9,7 +9,6 @@ module Axlsx # @see Worksheet#page_margins # @see Worksheet#initialize class PageMargins - include Axlsx::OptionsParser include Axlsx::SerializedAttributes @@ -20,7 +19,7 @@ module Axlsx # @option options [Numeric] top The top margin in inches # @option options [Numeric] header The header margin in inches # @option options [Numeric] footer The footer margin in inches - def initialize(options={}) + def initialize(options = {}) # Default values taken from MS Excel for Mac 2011 @left = @right = DEFAULT_LEFT_RIGHT @top = @bottom = DEFAULT_TOP_BOTTOM @@ -68,6 +67,7 @@ module Axlsx def set(margins) margins.select do |k, v| next unless [:left, :right, :top, :bottom, :header, :footer].include? k + send("#{k}=", v) end end diff --git a/lib/axlsx/workbook/worksheet/page_set_up_pr.rb b/lib/axlsx/workbook/worksheet/page_set_up_pr.rb index 03378a1a..819c5fa7 100644 --- a/lib/axlsx/workbook/worksheet/page_set_up_pr.rb +++ b/lib/axlsx/workbook/worksheet/page_set_up_pr.rb @@ -1,9 +1,7 @@ module Axlsx - # Page setup properties of the worksheet # This class name is not a typo, its spec. class PageSetUpPr - include Axlsx::OptionsParser include Axlsx::SerializedAttributes @@ -37,7 +35,7 @@ module Axlsx end # serialize to xml - def to_xml_string(str='') + def to_xml_string(str = '') str << ('<pageSetUpPr ' << serialized_attributes << '/>') end end diff --git a/lib/axlsx/workbook/worksheet/page_setup.rb b/lib/axlsx/workbook/worksheet/page_setup.rb index 9558579e..c10e28ce 100644 --- a/lib/axlsx/workbook/worksheet/page_setup.rb +++ b/lib/axlsx/workbook/worksheet/page_setup.rb @@ -5,7 +5,6 @@ module Axlsx # @see Worksheet#print_options # @see Worksheet#initialize class PageSetup - include Axlsx::OptionsParser include Axlsx::SerializedAttributes @@ -18,7 +17,7 @@ module Axlsx # @option options [Integer] scale Print scaling (percent value, integer ranging from 10 to 400) # @option options [Integer] paper_size - the size of paper to use def initialize(options = {}) - parse_options options + parse_options options end serializable_attributes :fit_to_height, :fit_to_width, :orientation, :paper_height, :paper_width, :scale, :paper_size @@ -65,124 +64,123 @@ module Axlsx attr_reader :scale # The paper size to use in printing - #1 = Letter paper (8.5 in. by 11 in.) - #2 = Letter small paper (8.5 in. by 11 in.) - #3 = Tabloid paper (11 in. by 17 in.) - #4 = Ledger paper (17 in. by 11 in.) - #5 = Legal paper (8.5 in. by 14 in.) - #6 = Statement paper (5.5 in. by 8.5 in.) - #7 = Executive paper (7.25 in. by 10.5 in.) - #8 = A3 paper (297 mm by 420 mm) - #9 = A4 paper (210 mm by 297 mm) - #10 = A4 small paper (210 mm by 297 mm) - #11 = A5 paper (148 mm by 210 mm) - #12 = B4 paper (250 mm by 353 mm) - #13 = B5 paper (176 mm by 250 mm) - #14 = Folio paper (8.5 in. by 13 in.) - #15 = Quarto paper (215 mm by 275 mm) - #16 = Standard paper (10 in. by 14 in.) - #17 = Standard paper (11 in. by 17 in.) - #18 = Note paper (8.5 in. by 11 in.) - #19 = #9 envelope (3.875 in. by 8.875 in.) - #20 = #10 envelope (4.125 in. by 9.5 in.) - #21 = #11 envelope (4.5 in. by 10.375 in.) - #22 = #12 envelope (4.75 in. by 11 in.) - #23 = #14 envelope (5 in. by 11.5 in.) 24 = C paper (17 in. by 22 in.) - #25 = D paper (22 in. by 34 in.) - #26 = E paper (34 in. by 44 in.) - #27 = DL envelope (110 mm by 220 mm) - #28 = C5 envelope (162 mm by 229 mm) - #29 = C3 envelope (324 mm by 458 mm) - #30 = C4 envelope (229 mm by 324 mm) - #31 = C6 envelope (114 mm by 162 mm) - #32 = C65 envelope (114 mm by 229 mm) - #33 = B4 envelope (250 mm by 353 mm) - #34 = B5 envelope (176 mm by 250 mm) - #35 = B6 envelope (176 mm by 125 mm) - #36 = Italy envelope (110 mm by 230 mm) - #37 = Monarch envelope (3.875 in. by 7.5 in.). 38 = 6 3/4 envelope (3.625 in. by 6.5 in.) - #39 = US standard fanfold (14.875 in. by 11 in.) - #40 = German standard fanfold (8.5 in. by 12 in.) - #41 = German legal fanfold (8.5 in. by 13 in.) - #42 = ISO B4 (250 mm by 353 mm) - #43 = Japanese double postcard (200 mm by 148 mm) - #44 = Standard paper (9 in. by 11 in.) - #45 = Standard paper (10 in. by 11 in.) - #46 = Standard paper (15 in. by 11 in.) - #47 = Invite envelope (220 mm by 220 mm) - #50 = Letter extra paper (9.275 in. by 12 in.) - #51 = Legal extra paper (9.275 in. by 15 in.) - #52 = Tabloid extra paper (11.69 in. by 18 in.) - #53 = A4 extra paper (236 mm by 322 mm) - #54 = Letter transverse paper (8.275 in. by 11 in.) - #55 = A4 transverse paper (210 mm by 297 mm) - #56 = Letter extra transverse paper (9.275 in. by 12 in.) - #57 = SuperA/SuperA/A4 paper (227 mm by 356 mm) - #58 = SuperB/SuperB/A3 paper (305 mm by 487 mm) - #59 = Letter plus paper (8.5 in. by 12.69 in.) - #60 = A4 plus paper (210 mm by 330 mm) - #61 = A5 transverse paper (148 mm by 210 mm) - #62 = JIS B5 transverse paper (182 mm by 257 mm) - #63 = A3 extra paper (322 mm by 445 mm) - #64 = A5 extra paper (174 mm by 235 mm) - #65 = ISO B5 extra paper (201 mm by 276 mm) - #66 = A2 paper (420 mm by 594 mm) - #67 = A3 transverse paper (297 mm by 420 mm) - #68 = A3 extra transverse paper (322 mm by 445 mm) - #69 = Japanese Double Postcard (200 mm x 148 mm) - #70 = A6 (105 mm x 148 mm - #71 = Japanese Envelope Kaku #2 - #72 = Japanese Envelope Kaku #3 - #73 = Japanese Envelope Chou #3 - #74 = Japanese Envelope Chou #4 - #75 = Letter Rotated (11in x 8 1/2 11 in) - #76 = A3 Rotated (420 mm x 297 mm) - #77 = A4 Rotated (297 mm x 210 mm) - #78 = A5 Rotated (210 mm x 148 mm) - #79 = B4 (JIS) Rotated (364 mm x 257 mm) - #80 = B5 (JIS) Rotated (257 mm x 182 mm) - #81 = Japanese Postcard Rotated (148 mm x 100 mm) - #82 = Double Japanese Postcard Rotated (148 mm x 200 mm) - #83 = A6 Rotated (148 mm x 105 mm) - #84 = Japanese Envelope Kaku #2 Rotated - #85 = Japanese Envelope Kaku #3 Rotated - #86 = Japanese Envelope Chou #3 Rotated - #87 = Japanese Envelope Chou #4 Rotated - #88 = B6 (JIS) (128 mm x 182 mm) - #89 = B6 (JIS) Rotated (182 mm x 128 mm) - #90 = (12 in x 11 in) - #91 = Japanese Envelope You #4 - #92 = Japanese Envelope You #4 Rotated - #93 = PRC 16K (146 mm x 215 mm) - #94 = PRC 32K (97 mm x 151 mm) - #95 = PRC 32K(Big) (97 mm x 151 mm) - #96 = PRC Envelope #1 (102 mm x 165 mm) - #97 = PRC Envelope #2 (102 mm x 176 mm) - #98 = PRC Envelope #3 (125 mm x 176 mm) - #99 = PRC Envelope #4 (110 mm x 208 mm) - #100 = PRC Envelope #5 (110 mm x 220 mm) - #101 = PRC Envelope #6 (120 mm x 230 mm) - #102 = PRC Envelope #7 (160 mm x 230 mm) - #103 = PRC Envelope #8 (120 mm x 309 mm) - #104 = PRC Envelope #9 (229 mm x 324 mm) - #105 = PRC Envelope #10 (324 mm x 458 mm) - #106 = PRC 16K Rotated - #107 = PRC 32K Rotated - #108 = PRC 32K(Big) Rotated - #109 = PRC Envelope #1 Rotated (165 mm x 102 mm) - #110 = PRC Envelope #2 Rotated (176 mm x 102 mm) - #111 = PRC Envelope #3 Rotated (176 mm x 125 mm) - #112 = PRC Envelope #4 Rotated (208 mm x 110 mm) - #113 = PRC Envelope #5 Rotated (220 mm x 110 mm) - #114 = PRC Envelope #6 Rotated (230 mm x 120 mm) - #115 = PRC Envelope #7 Rotated (230 mm x 160 mm) - #116 = PRC Envelope #8 Rotated (309 mm x 120 mm) - #117 = PRC Envelope #9 Rotated (324 mm x 229 mm) - #118 = PRC Envelope #10 Rotated (458 mm x 324 mm) + # 1 = Letter paper (8.5 in. by 11 in.) + # 2 = Letter small paper (8.5 in. by 11 in.) + # 3 = Tabloid paper (11 in. by 17 in.) + # 4 = Ledger paper (17 in. by 11 in.) + # 5 = Legal paper (8.5 in. by 14 in.) + # 6 = Statement paper (5.5 in. by 8.5 in.) + # 7 = Executive paper (7.25 in. by 10.5 in.) + # 8 = A3 paper (297 mm by 420 mm) + # 9 = A4 paper (210 mm by 297 mm) + # 10 = A4 small paper (210 mm by 297 mm) + # 11 = A5 paper (148 mm by 210 mm) + # 12 = B4 paper (250 mm by 353 mm) + # 13 = B5 paper (176 mm by 250 mm) + # 14 = Folio paper (8.5 in. by 13 in.) + # 15 = Quarto paper (215 mm by 275 mm) + # 16 = Standard paper (10 in. by 14 in.) + # 17 = Standard paper (11 in. by 17 in.) + # 18 = Note paper (8.5 in. by 11 in.) + # 19 = #9 envelope (3.875 in. by 8.875 in.) + # 20 = #10 envelope (4.125 in. by 9.5 in.) + # 21 = #11 envelope (4.5 in. by 10.375 in.) + # 22 = #12 envelope (4.75 in. by 11 in.) + # 23 = #14 envelope (5 in. by 11.5 in.) 24 = C paper (17 in. by 22 in.) + # 25 = D paper (22 in. by 34 in.) + # 26 = E paper (34 in. by 44 in.) + # 27 = DL envelope (110 mm by 220 mm) + # 28 = C5 envelope (162 mm by 229 mm) + # 29 = C3 envelope (324 mm by 458 mm) + # 30 = C4 envelope (229 mm by 324 mm) + # 31 = C6 envelope (114 mm by 162 mm) + # 32 = C65 envelope (114 mm by 229 mm) + # 33 = B4 envelope (250 mm by 353 mm) + # 34 = B5 envelope (176 mm by 250 mm) + # 35 = B6 envelope (176 mm by 125 mm) + # 36 = Italy envelope (110 mm by 230 mm) + # 37 = Monarch envelope (3.875 in. by 7.5 in.). 38 = 6 3/4 envelope (3.625 in. by 6.5 in.) + # 39 = US standard fanfold (14.875 in. by 11 in.) + # 40 = German standard fanfold (8.5 in. by 12 in.) + # 41 = German legal fanfold (8.5 in. by 13 in.) + # 42 = ISO B4 (250 mm by 353 mm) + # 43 = Japanese double postcard (200 mm by 148 mm) + # 44 = Standard paper (9 in. by 11 in.) + # 45 = Standard paper (10 in. by 11 in.) + # 46 = Standard paper (15 in. by 11 in.) + # 47 = Invite envelope (220 mm by 220 mm) + # 50 = Letter extra paper (9.275 in. by 12 in.) + # 51 = Legal extra paper (9.275 in. by 15 in.) + # 52 = Tabloid extra paper (11.69 in. by 18 in.) + # 53 = A4 extra paper (236 mm by 322 mm) + # 54 = Letter transverse paper (8.275 in. by 11 in.) + # 55 = A4 transverse paper (210 mm by 297 mm) + # 56 = Letter extra transverse paper (9.275 in. by 12 in.) + # 57 = SuperA/SuperA/A4 paper (227 mm by 356 mm) + # 58 = SuperB/SuperB/A3 paper (305 mm by 487 mm) + # 59 = Letter plus paper (8.5 in. by 12.69 in.) + # 60 = A4 plus paper (210 mm by 330 mm) + # 61 = A5 transverse paper (148 mm by 210 mm) + # 62 = JIS B5 transverse paper (182 mm by 257 mm) + # 63 = A3 extra paper (322 mm by 445 mm) + # 64 = A5 extra paper (174 mm by 235 mm) + # 65 = ISO B5 extra paper (201 mm by 276 mm) + # 66 = A2 paper (420 mm by 594 mm) + # 67 = A3 transverse paper (297 mm by 420 mm) + # 68 = A3 extra transverse paper (322 mm by 445 mm) + # 69 = Japanese Double Postcard (200 mm x 148 mm) + # 70 = A6 (105 mm x 148 mm + # 71 = Japanese Envelope Kaku #2 + # 72 = Japanese Envelope Kaku #3 + # 73 = Japanese Envelope Chou #3 + # 74 = Japanese Envelope Chou #4 + # 75 = Letter Rotated (11in x 8 1/2 11 in) + # 76 = A3 Rotated (420 mm x 297 mm) + # 77 = A4 Rotated (297 mm x 210 mm) + # 78 = A5 Rotated (210 mm x 148 mm) + # 79 = B4 (JIS) Rotated (364 mm x 257 mm) + # 80 = B5 (JIS) Rotated (257 mm x 182 mm) + # 81 = Japanese Postcard Rotated (148 mm x 100 mm) + # 82 = Double Japanese Postcard Rotated (148 mm x 200 mm) + # 83 = A6 Rotated (148 mm x 105 mm) + # 84 = Japanese Envelope Kaku #2 Rotated + # 85 = Japanese Envelope Kaku #3 Rotated + # 86 = Japanese Envelope Chou #3 Rotated + # 87 = Japanese Envelope Chou #4 Rotated + # 88 = B6 (JIS) (128 mm x 182 mm) + # 89 = B6 (JIS) Rotated (182 mm x 128 mm) + # 90 = (12 in x 11 in) + # 91 = Japanese Envelope You #4 + # 92 = Japanese Envelope You #4 Rotated + # 93 = PRC 16K (146 mm x 215 mm) + # 94 = PRC 32K (97 mm x 151 mm) + # 95 = PRC 32K(Big) (97 mm x 151 mm) + # 96 = PRC Envelope #1 (102 mm x 165 mm) + # 97 = PRC Envelope #2 (102 mm x 176 mm) + # 98 = PRC Envelope #3 (125 mm x 176 mm) + # 99 = PRC Envelope #4 (110 mm x 208 mm) + # 100 = PRC Envelope #5 (110 mm x 220 mm) + # 101 = PRC Envelope #6 (120 mm x 230 mm) + # 102 = PRC Envelope #7 (160 mm x 230 mm) + # 103 = PRC Envelope #8 (120 mm x 309 mm) + # 104 = PRC Envelope #9 (229 mm x 324 mm) + # 105 = PRC Envelope #10 (324 mm x 458 mm) + # 106 = PRC 16K Rotated + # 107 = PRC 32K Rotated + # 108 = PRC 32K(Big) Rotated + # 109 = PRC Envelope #1 Rotated (165 mm x 102 mm) + # 110 = PRC Envelope #2 Rotated (176 mm x 102 mm) + # 111 = PRC Envelope #3 Rotated (176 mm x 125 mm) + # 112 = PRC Envelope #4 Rotated (208 mm x 110 mm) + # 113 = PRC Envelope #5 Rotated (220 mm x 110 mm) + # 114 = PRC Envelope #6 Rotated (230 mm x 120 mm) + # 115 = PRC Envelope #7 Rotated (230 mm x 160 mm) + # 116 = PRC Envelope #8 Rotated (309 mm x 120 mm) + # 117 = PRC Envelope #9 Rotated (324 mm x 229 mm) + # 118 = PRC Envelope #10 Rotated (458 mm x 324 mm) # @return [Integer] attr_reader :paper_size - # Sets the paper size for printing. # @see PageSetup#paper_size # @return integer @@ -191,7 +189,7 @@ module Axlsx @paper_size = size end - # Set some or all page settings at once. + # Set some or all page settings at once. # @param [Hash] options The page settings to set (possible keys are :fit_to_height, :fit_to_width, :orientation, :paper_height, :paper_width, and :scale). def set(options) parse_options options @@ -215,13 +213,12 @@ module Axlsx # @note This method will overwrite any value you explicitly set via the fit_to_height or fit_to_width methods. # @option options [Integer] width The number of pages to fit this worksheet on horizontally. Default 999 # @option options [Integer] height The number of pages to fit this worksheet on vertically. Default 999 - def fit_to(options={}) + def fit_to(options = {}) self.fit_to_width = options[:width] || 999 self.fit_to_height = options[:height] || 999 [@fit_to_width, @fit_to_height] end - # helper method for worksheet to determine if the page setup is configured for fit to page printing # We treat any page set up that has a value set for fit_to_width or fit_to_height value as fit_to_page. # @return [Boolean] diff --git a/lib/axlsx/workbook/worksheet/pane.rb b/lib/axlsx/workbook/worksheet/pane.rb index 2bc77495..e752ab22 100644 --- a/lib/axlsx/workbook/worksheet/pane.rb +++ b/lib/axlsx/workbook/worksheet/pane.rb @@ -4,7 +4,6 @@ module Axlsx # @note The recommended way to manage the pane options is via SheetView#pane # @see SheetView#pane class Pane - include Axlsx::OptionsParser include Axlsx::SerializedAttributes # Creates a new {Pane} object @@ -13,8 +12,8 @@ module Axlsx # @option options [Cell, String] top_left_cell Top Left Visible Cell # @option options [Integer] x_split Horizontal Split Position # @option options [Integer] y_split Vertical Split Position - def initialize(options={}) - #defaults + def initialize(options = {}) + # defaults @active_pane = @state = @top_left_cell = nil @x_split = @y_split = 0 parse_options options @@ -24,16 +23,16 @@ module Axlsx # Active Pane # The pane that is active. - # Options are + # Options are # * bottom_left: Bottom left pane, when both vertical and horizontal # splits are applied. This value is also used when only - # a horizontal split has been applied, dividing the pane - # into upper and lower regions. In that case, this value + # a horizontal split has been applied, dividing the pane + # into upper and lower regions. In that case, this value # specifies the bottom pane. # * bottom_right: Bottom right pane, when both vertical and horizontal # splits are applied. # * top_left: Top left pane, when both vertical and horizontal splits - # are applied. This value is also used when only a horizontal + # are applied. This value is also used when only a horizontal # split has been applied, dividing the pane into upper and lower # regions. In that case, this value specifies the top pane. # This value is also used when only a vertical split has @@ -41,22 +40,21 @@ module Axlsx # regions. In that case, this value specifies the left pane # * top_right: Top right pane, when both vertical and horizontal # splits are applied. This value is also used when only - # a vertical split has been applied, dividing the pane - # into right and left regions. In that case, this value + # a vertical split has been applied, dividing the pane + # into right and left regions. In that case, this value # specifies the right pane. # @see type # @return [Symbol] # default nil attr_reader :active_pane - # Split State - # Indicates whether the pane has horizontal / vertical + # Indicates whether the pane has horizontal / vertical # splits, and whether those splits are frozen. - # Options are + # Options are # * frozen: Panes are frozen, but were not split being frozen. In # this state, when the panes are unfrozen again, a single - # pane results, with no split. In this state, the split + # pane results, with no split. In this state, the split # bars are not adjustable. # * frozen_split: Panes are frozen and were split before being frozen. In # this state, when the panes are unfrozen again, the split @@ -69,7 +67,7 @@ module Axlsx attr_reader :state # Top Left Visible Cell - # Location of the top left visible cell in the bottom + # Location of the top left visible cell in the bottom # right pane (when in Left-To-Right mode). # @see type # @return [String] @@ -78,7 +76,7 @@ module Axlsx # Horizontal Split Position # Horizontal position of the split, in 1/20th of a point; 0 (zero) - # if none. If the pane is frozen, this value indicates the number + # if none. If the pane is frozen, this value indicates the number # of columns visible in the top pane. # @see type # @return [Integer] @@ -86,7 +84,7 @@ module Axlsx attr_reader :x_split # Vertical Split Position - # Vertical position of the split, in 1/20th of a point; 0 (zero) + # Vertical position of the split, in 1/20th of a point; 0 (zero) # if none. If the pane is frozen, this value indicates the number # of rows visible in the left pane. # @see type @@ -126,13 +124,14 @@ module Axlsx finalize serialized_tag 'pane', str end + private def finalize if @state == 'frozen' && @top_left_cell.nil? row = @y_split || 0 column = @x_split || 0 - @top_left_cell = "#{('A'..'ZZ').to_a[column]}#{row+1}" + @top_left_cell = "#{('A'..'ZZ').to_a[column]}#{row + 1}" end end end diff --git a/lib/axlsx/workbook/worksheet/pivot_table.rb b/lib/axlsx/workbook/worksheet/pivot_table.rb index 455665a5..ff131dfb 100644 --- a/lib/axlsx/workbook/worksheet/pivot_table.rb +++ b/lib/axlsx/workbook/worksheet/pivot_table.rb @@ -1,10 +1,8 @@ -# encoding: UTF-8 module Axlsx # Table # @note Worksheet#add_pivot_table is the recommended way to create tables for your worksheets. # @see README for examples class PivotTable - include Axlsx::OptionsParser # Creates a new PivotTable object @@ -13,12 +11,12 @@ module Axlsx # @param [Worksheet] sheet The sheet containing the table data. # @option options [Cell, String] name # @option options [TableStyle] style - def initialize(ref, range, sheet, options={}) + def initialize(ref, range, sheet, options = {}) @ref = ref self.range = range @sheet = sheet @sheet.workbook.pivot_tables << self - @name = "PivotTable#{index+1}" + @name = "PivotTable#{index + 1}" @data_sheet = nil @rows = [] @columns = [] @@ -92,7 +90,6 @@ module Axlsx # @return [Array] attr_reader :rows - # (see #rows) def rows=(v) DataTypeValidator.validate "#{self.class}.rows", [Array], v @@ -125,7 +122,7 @@ module Axlsx @data = [] v.each do |data_field| if data_field.is_a? String - data_field = {:ref => data_field} + data_field = { :ref => data_field } end data_field.each do |key, value| if key == :num_fmt @@ -161,13 +158,13 @@ module Axlsx # The part name for this table # @return [String] def pn - "#{PIVOT_TABLE_PN % (index+1)}" + "#{PIVOT_TABLE_PN % (index + 1)}" end # The relationship part name of this pivot table # @return [String] def rels_pn - "#{PIVOT_TABLE_RELS_PN % (index+1)}" + "#{PIVOT_TABLE_RELS_PN % (index + 1)}" end # The cache_definition for this pivot table @@ -222,7 +219,7 @@ module Axlsx str << '<colFields count="1"><field x="-2"/></colFields>' str << "<colItems count=\"#{data.size}\">" str << '<i><x/></i>' - data[1..-1].each_with_index do |datum_value,i| + data[1..-1].each_with_index do |datum_value, i| str << "<i i=\"#{i + 1}\"><x v=\"#{i + 1}\"/></i>" end str << '</colItems>' @@ -247,7 +244,7 @@ module Axlsx str << "<dataFields count=\"#{data.size}\">" data.each do |datum_value| # The correct name prefix in ["Sum","Average", etc...] - str << "<dataField name='#{(datum_value[:subtotal]||'')} of #{datum_value[:ref]}' fld='#{header_index_of(datum_value[:ref])}' baseField='0' baseItem='0'" + str << "<dataField name='#{(datum_value[:subtotal] || '')} of #{datum_value[:ref]}' fld='#{header_index_of(datum_value[:ref])}' baseField='0' baseItem='0'" str << " numFmtId='#{datum_value[:num_fmt]}'" if datum_value[:num_fmt] str << " subtotal='#{datum_value[:subtotal]}' " if datum_value[:subtotal] str << "/>" @@ -257,7 +254,7 @@ module Axlsx # custom pivot table style unless style_info.empty? str << '<pivotTableStyleInfo' - style_info.each do |k,v| + style_info.each do |k, v| str << ' ' << k.to_s << '="' << v.to_s << '"' end str << ' />' diff --git a/lib/axlsx/workbook/worksheet/pivot_table_cache_definition.rb b/lib/axlsx/workbook/worksheet/pivot_table_cache_definition.rb index 969b0bf2..8813c84b 100644 --- a/lib/axlsx/workbook/worksheet/pivot_table_cache_definition.rb +++ b/lib/axlsx/workbook/worksheet/pivot_table_cache_definition.rb @@ -1,10 +1,8 @@ -# encoding: UTF-8 module Axlsx # Table # @note Worksheet#add_pivot_table is the recommended way to create tables for your worksheets. # @see README for examples class PivotTableCacheDefinition - include Axlsx::OptionsParser # Creates a new PivotTable object @@ -26,7 +24,7 @@ module Axlsx # The part name for this table # @return [String] def pn - "#{PIVOT_TABLE_CACHE_DEFINITION_PN % (index+1)}" + "#{PIVOT_TABLE_CACHE_DEFINITION_PN % (index + 1)}" end # The identifier for this cache @@ -48,19 +46,18 @@ module Axlsx def to_xml_string(str = '') str << '<?xml version="1.0" encoding="UTF-8"?>' str << ('<pivotCacheDefinition xmlns="' << XML_NS << '" xmlns:r="' << XML_NS_R << '" invalid="1" refreshOnLoad="1" recordCount="0">') - str << '<cacheSource type="worksheet">' - str << ( '<worksheetSource ref="' << pivot_table.range << '" sheet="' << pivot_table.data_sheet.name << '"/>') - str << '</cacheSource>' - str << ( '<cacheFields count="' << pivot_table.header_cells_count.to_s << '">') + str << '<cacheSource type="worksheet">' + str << ('<worksheetSource ref="' << pivot_table.range << '" sheet="' << pivot_table.data_sheet.name << '"/>') + str << '</cacheSource>' + str << ('<cacheFields count="' << pivot_table.header_cells_count.to_s << '">') pivot_table.header_cells.each do |cell| - str << ( '<cacheField name="' << cell.clean_value << '" numFmtId="0">') + str << ('<cacheField name="' << cell.clean_value << '" numFmtId="0">') str << '<sharedItems count="0">' str << '</sharedItems>' - str << '</cacheField>' + str << '</cacheField>' end - str << '</cacheFields>' + str << '</cacheFields>' str << '</pivotCacheDefinition>' end - end end diff --git a/lib/axlsx/workbook/worksheet/pivot_tables.rb b/lib/axlsx/workbook/worksheet/pivot_tables.rb index 912d9f41..c27162c3 100644 --- a/lib/axlsx/workbook/worksheet/pivot_tables.rb +++ b/lib/axlsx/workbook/worksheet/pivot_tables.rb @@ -1,11 +1,10 @@ module Axlsx - # A simple, self serializing class for storing pivot tables class PivotTables < SimpleTypedList - # creates a new Tables object def initialize(worksheet) raise ArgumentError, "you must provide a worksheet" unless worksheet.is_a?(Worksheet) + super PivotTable @worksheet = worksheet end @@ -17,8 +16,8 @@ module Axlsx # returns the relationships required by this collection def relationships return [] if empty? - map{ |pivot_table| Relationship.new(pivot_table, PIVOT_TABLE_R, "../#{pivot_table.pn}") } + + map { |pivot_table| Relationship.new(pivot_table, PIVOT_TABLE_R, "../#{pivot_table.pn}") } end end - end diff --git a/lib/axlsx/workbook/worksheet/print_options.rb b/lib/axlsx/workbook/worksheet/print_options.rb index e57c2094..7ba52861 100644 --- a/lib/axlsx/workbook/worksheet/print_options.rb +++ b/lib/axlsx/workbook/worksheet/print_options.rb @@ -5,7 +5,6 @@ module Axlsx # @see Worksheet#print_options # @see Worksheet#initialize class PrintOptions - include Axlsx::OptionsParser include Axlsx::SerializedAttributes include Axlsx::Accessors diff --git a/lib/axlsx/workbook/worksheet/protected_range.rb b/lib/axlsx/workbook/worksheet/protected_range.rb index e990f1cb..e4eb83e5 100644 --- a/lib/axlsx/workbook/worksheet/protected_range.rb +++ b/lib/axlsx/workbook/worksheet/protected_range.rb @@ -3,14 +3,13 @@ module Axlsx # @note the recommended way to manage protected ranges with via Worksheet#protect_range # @see Worksheet#protect_range class ProtectedRange - include Axlsx::OptionsParser include Axlsx::SerializedAttributes - # Initializes a new protected range object + # Initializes a new protected range object # @option [String] sqref The cell range reference to protect. This can be an absolute or a relateve range however, it only applies to the current sheet. # @option [String] name An optional name for the protected name. - def initialize(options={}) + def initialize(options = {}) parse_options options yield self if block_given? end @@ -40,8 +39,8 @@ module Axlsx # @param [String] str if this string object is provided we append # our output to that object. Use this - it helps limit the number of # objects created during serialization - def to_xml_string(str="") + def to_xml_string(str = "") serialized_tag 'protectedRange', str - end + end end end diff --git a/lib/axlsx/workbook/worksheet/protected_ranges.rb b/lib/axlsx/workbook/worksheet/protected_ranges.rb index d274cf80..75b3aee5 100644 --- a/lib/axlsx/workbook/worksheet/protected_ranges.rb +++ b/lib/axlsx/workbook/worksheet/protected_ranges.rb @@ -1,13 +1,12 @@ module Axlsx - # A self serializing collection of ranges that should be protected in # the worksheet class ProtectedRanges < SimpleTypedList - attr_reader :worksheet def initialize(worksheet) raise ArgumentError, 'You must provide a worksheet' unless worksheet.is_a?(Worksheet) + super ProtectedRange @worksheet = worksheet end @@ -15,13 +14,13 @@ module Axlsx # Adds a protected range # @param [Array|String] cells A string range reference or array of cells that will be protected def add_range(cells) - sqref = if cells.is_a?(String) - cells - elsif cells.is_a?(SimpleTypedList) || cells.is_a?(Array) - Axlsx::cell_range(cells, false) - end - self << ProtectedRange.new(:sqref => sqref, :name => "Range#{size}") - last + sqref = if cells.is_a?(String) + cells + elsif cells.is_a?(SimpleTypedList) || cells.is_a?(Array) + Axlsx::cell_range(cells, false) + end + self << ProtectedRange.new(:sqref => sqref, :name => "Range#{size}") + last end # Serializes the protected ranges @@ -29,6 +28,7 @@ module Axlsx # @return [String] def to_xml_string(str = '') return if empty? + str << '<protectedRanges>' each { |range| range.to_xml_string(str) } str << '</protectedRanges>' diff --git a/lib/axlsx/workbook/worksheet/rich_text.rb b/lib/axlsx/workbook/worksheet/rich_text.rb index 81af32b2..4b643470 100644 --- a/lib/axlsx/workbook/worksheet/rich_text.rb +++ b/lib/axlsx/workbook/worksheet/rich_text.rb @@ -1,13 +1,11 @@ module Axlsx - # A simple, self serializing class for storing TextRuns class RichText < SimpleTypedList - # creates a new RichText collection # @param [String] text -optional The text to use in creating the first RichTextRun # @param [Object] options -optional The options to use in creating the first RichTextRun # @yield [RichText] self - def initialize(text = nil, options={}) + def initialize(text = nil, options = {}) super(RichTextRun) add_run(text, options) unless text.nil? yield self if block_given? @@ -34,7 +32,7 @@ module Axlsx # Creates and adds a RichTextRun to this collectino # @param [String] text The text to use in creating a new RichTextRun # @param [Object] options The options to use in creating the new RichTextRun - def add_run(text, options={}) + def add_run(text, options = {}) self << RichTextRun.new(text, options) end @@ -47,8 +45,8 @@ module Axlsx # renders the RichTextRuns in this collection # @param [String] str # @return [String] - def to_xml_string(str='') - each{ |run| run.to_xml_string(str) } + def to_xml_string(str = '') + each { |run| run.to_xml_string(str) } str end end diff --git a/lib/axlsx/workbook/worksheet/rich_text_run.rb b/lib/axlsx/workbook/worksheet/rich_text_run.rb index b3870672..78639575 100644 --- a/lib/axlsx/workbook/worksheet/rich_text_run.rb +++ b/lib/axlsx/workbook/worksheet/rich_text_run.rb @@ -1,8 +1,6 @@ module Axlsx - # The RichTextRun class creates and self serializing text run. class RichTextRun - include Axlsx::OptionsParser attr_reader :value @@ -13,7 +11,7 @@ module Axlsx :shadow, :condense, :extend, :u, :vertAlign, :sz, :color, :scheme].freeze - def initialize(value, options={}) + def initialize(value, options = {}) self.value = value parse_options(options) end @@ -27,6 +25,7 @@ module Axlsx # The inline font_name property for the cell # @return [String] attr_reader :font_name + # @see font_name def font_name=(v) set_run_style :validate_string, :font_name, v; end @@ -53,6 +52,7 @@ module Axlsx # 255  OEM_CHARSET # @return [String] attr_reader :charset + # @see charset def charset=(v) set_run_style :validate_unsigned_int, :charset, v; end @@ -64,6 +64,7 @@ module Axlsx # 4 Script # 5 Decorative attr_reader :family + # @see family def family=(v) set_run_style :validate_family, :family, v.to_i @@ -72,42 +73,49 @@ module Axlsx # The inline bold property for the cell # @return [Boolean] attr_reader :b + # @see b def b=(v) set_run_style :validate_boolean, :b, v; end # The inline italic property for the cell # @return [Boolean] attr_reader :i + # @see i def i=(v) set_run_style :validate_boolean, :i, v; end # The inline strike property for the cell # @return [Boolean] attr_reader :strike + # @see strike def strike=(v) set_run_style :validate_boolean, :strike, v; end # The inline outline property for the cell # @return [Boolean] attr_reader :outline + # @see outline def outline=(v) set_run_style :validate_boolean, :outline, v; end # The inline shadow property for the cell # @return [Boolean] attr_reader :shadow + # @see shadow def shadow=(v) set_run_style :validate_boolean, :shadow, v; end # The inline condense property for the cell # @return [Boolean] attr_reader :condense + # @see condense def condense=(v) set_run_style :validate_boolean, :condense, v; end # The inline extend property for the cell # @return [Boolean] attr_reader :extend + # @see extend def extend=(v) set_run_style :validate_boolean, :extend, v; end @@ -117,6 +125,7 @@ module Axlsx # @return [String] # @note true is for backwards compatability and is reassigned to :single attr_reader :u + # @see u def u=(v) v = :single if (v == true || v == 1 || v == :true || v == 'true') @@ -126,14 +135,16 @@ module Axlsx # The inline color property for the cell # @return [Color] attr_reader :color + # @param [String] v The 8 character representation for an rgb color #FFFFFFFF" def color=(v) - @color = v.is_a?(Color) ? v : Color.new(:rgb=>v) + @color = v.is_a?(Color) ? v : Color.new(:rgb => v) end # The inline sz property for the cell # @return [Inteter] attr_reader :sz + # @see sz def sz=(v) set_run_style :validate_unsigned_int, :sz, v; end @@ -141,6 +152,7 @@ module Axlsx # this must be one of [:baseline, :subscript, :superscript] # @return [Symbol] attr_reader :vertAlign + # @see vertAlign def vertAlign=(v) RestrictionValidator.validate :cell_vertAlign, [:baseline, :subscript, :superscript], v @@ -151,6 +163,7 @@ module Axlsx # this must be one of [:none, major, minor] # @return [Symbol] attr_reader :scheme + # @see scheme def scheme=(v) RestrictionValidator.validate :cell_scheme, [:none, :major, :minor], v @@ -162,6 +175,7 @@ module Axlsx # @return [Array] def autowidth(widtharray) return if value.nil? + if styles.cellXfs[style].alignment && styles.cellXfs[style].alignment.wrap_text first = true value.to_s.split(/\r?\n/, -1).each do |line| @@ -181,6 +195,7 @@ module Axlsx # Utility method for setting inline style attributes def set_run_style(validator, attr, value) return unless INLINE_STYLES.include?(attr.to_sym) + Axlsx.send(validator, value) unless validator.nil? self.instance_variable_set :"@#{attr.to_s}", value end @@ -190,7 +205,7 @@ module Axlsx # @return [String] def to_xml_string(str = '') valid = RichTextRun::INLINE_STYLES - data = Hash[Axlsx.instance_values_for(self).map{ |k, v| [k.to_sym, v] }] + data = Hash[Axlsx.instance_values_for(self).map { |k, v| [k.to_sym, v] }] data = data.select { |key, value| valid.include?(key) && !value.nil? } str << '<r><rPr>' @@ -223,6 +238,7 @@ module Axlsx # imagemagick and loading metrics for every character. def font_size return sz if sz + font = styles.fonts[styles.cellXfs[style].fontId] || styles.fonts[0] (font.b || (defined?(@b) && @b)) ? (font.sz * 1.5) : font.sz end diff --git a/lib/axlsx/workbook/worksheet/row.rb b/lib/axlsx/workbook/worksheet/row.rb index 63a8d328..453e1e66 100644 --- a/lib/axlsx/workbook/worksheet/row.rb +++ b/lib/axlsx/workbook/worksheet/row.rb @@ -1,4 +1,3 @@ -# encoding: UTF-8 module Axlsx # A Row is a single row in a worksheet. # @note The recommended way to manage rows and cells is to use Worksheet#add_row @@ -6,13 +5,13 @@ module Axlsx class Row < SimpleTypedList include SerializedAttributes include Accessors - + # No support is provided for the following attributes # spans # thickTop # thickBottom - # Creates a new row. New Cell objects are created based on the values, types and style options. + # Creates a new row. New Cell objects are created based on the values, types and style options. # A new cell is created for each item in the values array. style and types options are applied as follows: # If the types option is defined and is a symbol it is applied to all the cells created. # If the types option is an array, cell types are applied by index for each cell @@ -28,7 +27,7 @@ module Axlsx # @option options [Integer] offset - add empty columns before values # @see Row#array_to_cells # @see Cell - def initialize(worksheet, values=[], options={}) + def initialize(worksheet, values = [], options = {}) self.worksheet = worksheet super(Cell, nil, values.size + options[:offset].to_i) self.height = options.delete(:height) @@ -64,7 +63,7 @@ module Axlsx # @see Row#s def s=(v) Axlsx.validate_unsigned_numeric(v) - @custom_format = true + @custom_format = true @s = v end @@ -73,7 +72,7 @@ module Axlsx Axlsx.validate_unsigned_numeric(v) @outline_level = v end - + alias :outlineLevel= :outline_level= # The index of this row in the worksheet @@ -106,14 +105,14 @@ module Axlsx # sets the color for every cell in this row def color=(color) - each_with_index do | cell, index | + each_with_index do |cell, index| cell.color = color.is_a?(Array) ? color[index] : color end end # sets the style for every cell in this row def style=(style) - each_with_index do | cell, index | + each_with_index do |cell, index| cell.style = style.is_a?(Array) ? style[index] : style end end @@ -126,7 +125,7 @@ module Axlsx @ht = v end end - + # return cells def cells self @@ -135,7 +134,7 @@ module Axlsx private # assigns the owning worksheet for this row - def worksheet=(v) DataTypeValidator.validate :row_worksheet, Worksheet, v; @worksheet=v; end + def worksheet=(v) DataTypeValidator.validate :row_worksheet, Worksheet, v; @worksheet = v; end # Converts values, types, and style options into cells and associates them with this row. # A new cell is created for each item in the values array. @@ -146,7 +145,7 @@ module Axlsx # @option options [Array] values # @option options [Array, Symbol] types # @option options [Array, Integer] style - def array_to_cells(values, options={}) + def array_to_cells(values, options = {}) DataTypeValidator.validate :array_to_cells, Array, values types, style, formula_values, escape_formulas, offset = options.delete(:types), options.delete(:style), options.delete(:formula_values), options.delete(:escape_formulas), options.delete(:offset) offset.to_i.times { |index| self[index] = Cell.new(self) } if offset @@ -160,5 +159,4 @@ module Axlsx end end end - end diff --git a/lib/axlsx/workbook/worksheet/row_breaks.rb b/lib/axlsx/workbook/worksheet/row_breaks.rb index c6ec89a9..2da31719 100644 --- a/lib/axlsx/workbook/worksheet/row_breaks.rb +++ b/lib/axlsx/workbook/worksheet/row_breaks.rb @@ -1,9 +1,7 @@ module Axlsx - # A collection of break objects that define row breaks (page breaks) for printing and preview class RowBreaks < SimpleTypedList - def initialize super Break end @@ -17,14 +15,15 @@ module Axlsx self << Break.new(options.merge(:max => 16383, :man => true)) last end - + # <rowBreaks count="3" manualBreakCount="3"> # <brk id="1" max="16383" man="1"/> # <brk id="7" max="16383" man="1"/> # <brk id="13" max="16383" man="1"/> # </rowBreaks> - def to_xml_string(str='') + def to_xml_string(str = '') return if empty? + str << ('<rowBreaks count="' << self.size.to_s << '" manualBreakCount="' << self.size.to_s << '">') each { |brk| brk.to_xml_string(str) } str << '</rowBreaks>' diff --git a/lib/axlsx/workbook/worksheet/selection.rb b/lib/axlsx/workbook/worksheet/selection.rb index fcb06c13..82538fce 100644 --- a/lib/axlsx/workbook/worksheet/selection.rb +++ b/lib/axlsx/workbook/worksheet/selection.rb @@ -1,11 +1,9 @@ -# encoding: UTF-8 module Axlsx # Selection options for worksheet panes. # # @note The recommended way to manage the selection pane options is via SheetView#add_selection # @see SheetView#add_selection class Selection - include Axlsx::OptionsParser include Axlsx::SerializedAttributes @@ -14,7 +12,7 @@ module Axlsx # @option options [Integer] active_cell_id Active Cell Index # @option options [Symbol] pane Pane # @option options [String] sqref Sequence of References - def initialize(options={}) + def initialize(options = {}) @active_cell = @active_cell_id = @pane = @sqref = nil parse_options options end @@ -40,16 +38,16 @@ module Axlsx # Pane # The pane to which this selection belongs. - # Options are + # Options are # * bottom_left: Bottom left pane, when both vertical and horizontal # splits are applied. This value is also used when only - # a horizontal split has been applied, dividing the pane - # into upper and lower regions. In that case, this value + # a horizontal split has been applied, dividing the pane + # into upper and lower regions. In that case, this value # specifies the bottom pane. # * bottom_right: Bottom right pane, when both vertical and horizontal # splits are applied. # * top_left: Top left pane, when both vertical and horizontal splits - # are applied. This value is also used when only a horizontal + # are applied. This value is also used when only a horizontal # split has been applied, dividing the pane into upper and lower # regions. In that case, this value specifies the top pane. # This value is also used when only a vertical split has @@ -57,8 +55,8 @@ module Axlsx # regions. In that case, this value specifies the left pane # * top_right: Top right pane, when both vertical and horizontal # splits are applied. This value is also used when only - # a vertical split has been applied, dividing the pane - # into right and left regions. In that case, this value + # a vertical split has been applied, dividing the pane + # into right and left regions. In that case, this value # specifies the right pane. # @see type # @return [Symbol] diff --git a/lib/axlsx/workbook/worksheet/sheet_calc_pr.rb b/lib/axlsx/workbook/worksheet/sheet_calc_pr.rb index 88ada9ae..d692d461 100644 --- a/lib/axlsx/workbook/worksheet/sheet_calc_pr.rb +++ b/lib/axlsx/workbook/worksheet/sheet_calc_pr.rb @@ -1,15 +1,14 @@ module Axlsx - # the SheetCalcPr object for the worksheet # This object contains calculation properties for the worksheet. class SheetCalcPr - include Axlsx::OptionsParser - include Axlsx::SerializedAttributes - include Axlsx::Accessors + include Axlsx::OptionsParser + include Axlsx::SerializedAttributes + include Axlsx::Accessors # creates a new SheetCalcPr # @param [Hash] options Options for this object # @option [Boolean] full_calc_on_load @see full_calc_on_load - def initialize(options={}) + def initialize(options = {}) @full_calc_on_load = true parse_options options end @@ -22,7 +21,7 @@ module Axlsx # @param [String] str the string to append this objects serialized # content to. # @return [String] - def to_xml_string(str='') + def to_xml_string(str = '') str << "<sheetCalcPr #{serialized_attributes}/>" end end diff --git a/lib/axlsx/workbook/worksheet/sheet_data.rb b/lib/axlsx/workbook/worksheet/sheet_data.rb index a7b8735b..f6a27b0e 100644 --- a/lib/axlsx/workbook/worksheet/sheet_data.rb +++ b/lib/axlsx/workbook/worksheet/sheet_data.rb @@ -1,15 +1,14 @@ module Axlsx - # This class manages the serialization of rows for worksheets class SheetData - # Creates a new SheetData object # @param [Worksheet] worksheet The worksheet that owns this sheet data. def initialize(worksheet) raise ArgumentError, "you must provide a worksheet" unless worksheet.is_a?(Worksheet) + @worksheet = worksheet end - + attr_reader :worksheet # Serialize the sheet data @@ -17,11 +16,10 @@ module Axlsx # @return [String] def to_xml_string(str = '') str << '<sheetData>' - worksheet.rows.each_with_index do |row, index| - row.to_xml_string(index, str) + worksheet.rows.each_with_index do |row, index| + row.to_xml_string(index, str) end str << '</sheetData>' end - end end diff --git a/lib/axlsx/workbook/worksheet/sheet_format_pr.rb b/lib/axlsx/workbook/worksheet/sheet_format_pr.rb index fc9ce3a3..ad4e4fab 100644 --- a/lib/axlsx/workbook/worksheet/sheet_format_pr.rb +++ b/lib/axlsx/workbook/worksheet/sheet_format_pr.rb @@ -1,17 +1,16 @@ module Axlsx - - #Sheet formatting properties - # <xsd:complexType name="CT_SheetFormatPr">
- # <xsd:attribute name="baseColWidth" type="xsd:unsignedInt" use="optional" default="8"/>
- # <xsd:attribute name="defaultColWidth" type="xsd:double" use="optional"/>
- # <xsd:attribute name="defaultRowHeight" type="xsd:double" use="required"/>
- # <xsd:attribute name="customHeight" type="xsd:boolean" use="optional" default="false"/>
- # <xsd:attribute name="zeroHeight" type="xsd:boolean" use="optional" default="false"/>
- # <xsd:attribute name="thickTop" type="xsd:boolean" use="optional" default="false"/>
- # <xsd:attribute name="thickBottom" type="xsd:boolean" use="optional" default="false"/>
- # <xsd:attribute name="outlineLevelRow" type="xsd:unsignedByte" use="optional" default="0"/>
- # <xsd:attribute name="outlineLevelCol" type="xsd:unsignedByte" use="optional" default="0"/>
- #</xsd:complexType>
+ # Sheet formatting properties + # <xsd:complexType name="CT_SheetFormatPr"> + # <xsd:attribute name="baseColWidth" type="xsd:unsignedInt" use="optional" default="8"/> + # <xsd:attribute name="defaultColWidth" type="xsd:double" use="optional"/> + # <xsd:attribute name="defaultRowHeight" type="xsd:double" use="required"/> + # <xsd:attribute name="customHeight" type="xsd:boolean" use="optional" default="false"/> + # <xsd:attribute name="zeroHeight" type="xsd:boolean" use="optional" default="false"/> + # <xsd:attribute name="thickTop" type="xsd:boolean" use="optional" default="false"/> + # <xsd:attribute name="thickBottom" type="xsd:boolean" use="optional" default="false"/> + # <xsd:attribute name="outlineLevelRow" type="xsd:unsignedByte" use="optional" default="0"/> + # <xsd:attribute name="outlineLevelCol" type="xsd:unsignedByte" use="optional" default="0"/> + # </xsd:complexType> class SheetFormatPr include Axlsx::SerializedAttributes @@ -29,29 +28,30 @@ module Axlsx # @option [Boolean] thick_bottom 'True' if rows have a thick bottom border by default. # @option [Integer] outline_level_row Highest number of outline level for rows in this sheet. These values shall be in synch with the actual sheet outline levels. # @option [Integer] outline_level_col Highest number of outline levels for columns in this sheet. These values shall be in synch with the actual sheet outline levels. - def initialize(options={}) + def initialize(options = {}) set_defaults parse_options options end serializable_attributes :base_col_width, :default_col_width, :default_row_height, - :custom_height, :zero_height, :thick_top, :thick_bottom, - :outline_level_row, :outline_level_col + :custom_height, :zero_height, :thick_top, :thick_bottom, + :outline_level_row, :outline_level_col float_attr_accessor :default_col_width, :default_row_height boolean_attr_accessor :custom_height, :zero_height, :thick_top, :thick_bottom - unsigned_int_attr_accessor :base_col_width, :outline_level_row, :outline_level_col + unsigned_int_attr_accessor :base_col_width, :outline_level_row, :outline_level_col # serializes this object to an xml string # @param [String] str The string this objects serialization will be appended to # @return [String] - def to_xml_string(str='') + def to_xml_string(str = '') str << "<sheetFormatPr #{serialized_attributes}/>" end private + def set_defaults @base_col_width = 8 @default_row_height = 18 diff --git a/lib/axlsx/workbook/worksheet/sheet_pr.rb b/lib/axlsx/workbook/worksheet/sheet_pr.rb index 72028141..4fccf662 100644 --- a/lib/axlsx/workbook/worksheet/sheet_pr.rb +++ b/lib/axlsx/workbook/worksheet/sheet_pr.rb @@ -1,5 +1,4 @@ module Axlsx - # The SheetPr class manages serialization of a worksheet's sheetPr element. class SheetPr include Axlsx::OptionsParser @@ -30,8 +29,9 @@ module Axlsx # Creates a new SheetPr object # @param [Worksheet] worksheet The worksheet that owns this SheetPr object - def initialize(worksheet, options={}) + def initialize(worksheet, options = {}) raise ArgumentError, "you must provide a worksheet" unless worksheet.is_a?(Worksheet) + @worksheet = worksheet @outline_pr = nil parse_options options @@ -62,7 +62,7 @@ module Axlsx def page_setup_pr @page_setup_pr ||= PageSetUpPr.new end - + # The OutlinePr for this sheet pr object # @return [OutlinePr] def outline_pr diff --git a/lib/axlsx/workbook/worksheet/sheet_protection.rb b/lib/axlsx/workbook/worksheet/sheet_protection.rb index c6142be5..7433d5bb 100644 --- a/lib/axlsx/workbook/worksheet/sheet_protection.rb +++ b/lib/axlsx/workbook/worksheet/sheet_protection.rb @@ -1,9 +1,6 @@ -# encoding: UTF-8 module Axlsx - # The SheetProtection object manages worksheet protection options per sheet. class SheetProtection - include Axlsx::OptionsParser include Axlsx::SerializedAttributes include Axlsx::Accessors @@ -26,7 +23,7 @@ module Axlsx # @option options [Boolean] pivot_tables @see SheetProtection#pivot_tables # @option options [Boolean] select_unlocked_cells @see SheetProtection#select_unlocked_cells # @option options [String] password. The password required for unlocking. @see SheetProtection#password= - def initialize(options={}) + def initialize(options = {}) @objects = @scenarios = @select_locked_cells = @select_unlocked_cells = false @sheet = @format_cells = @format_rows = @format_columns = @insert_columns = @insert_rows = @insert_hyperlinks = @delete_columns = @delete_rows = @sort = @auto_filter = @pivot_tables = true @password = nil @@ -34,12 +31,12 @@ module Axlsx end boolean_attr_accessor :sheet, :objects, :scenarios, :format_cells, :format_columns, :format_rows, - :insert_columns, :insert_rows, :insert_hyperlinks, :delete_columns, :delete_rows, - :select_locked_cells, :sort, :auto_filter, :pivot_tables, :select_unlocked_cells + :insert_columns, :insert_rows, :insert_hyperlinks, :delete_columns, :delete_rows, + :select_locked_cells, :sort, :auto_filter, :pivot_tables, :select_unlocked_cells serializable_attributes :sheet, :objects, :scenarios, :format_cells, :format_columns, :format_rows, - :insert_columns, :insert_rows, :insert_hyperlinks, :delete_columns, :delete_rows, - :select_locked_cells, :sort, :auto_filter, :pivot_tables, :select_unlocked_cells, :salt, :password + :insert_columns, :insert_rows, :insert_hyperlinks, :delete_columns, :delete_rows, + :select_locked_cells, :sort, :auto_filter, :pivot_tables, :select_unlocked_cells, :salt, :password # Specifies the salt which was prepended to the user-supplied password before it was hashed using the hashing algorithm # @return [String] @@ -50,9 +47,9 @@ module Axlsx # default nil attr_reader :password - # This block is intended to implement the salt_value, hash_value and spin count as per the ECMA-376 standard. - # However, it does not seem to actually work in EXCEL - instead they are using their old retro algorithm shown below - # defined in the transitional portion of the speck. I am leaving this code in in the hope that someday Ill be able to + # This block is intended to implement the salt_value, hash_value and spin count as per the ECMA-376 standard. + # However, it does not seem to actually work in EXCEL - instead they are using their old retro algorithm shown below + # defined in the transitional portion of the speck. I am leaving this code in in the hope that someday Ill be able to # figure out why it does not work, and if Excel even supports it. # def propper_password=(v) # @algorithm_name = v == nil ? nil : 'SHA-1' @@ -69,6 +66,7 @@ module Axlsx # encodes password for protection locking def password=(v) return if v == nil + @password = create_password_hash(v) end @@ -80,6 +78,7 @@ module Axlsx end private + # Creates a password hash for a given password # @return [String] def create_password_hash(password) @@ -102,14 +101,14 @@ module Axlsx chars.collect! do |char| i += 1 - char = char.unpack('c')[0] << i #ord << i + char = char.unpack('c')[0] << i # ord << i low_15 = char & 0x7fff high_15 = char & 0x7fff << 15 high_15 = high_15 >> 15 char = low_15 | high_15 end - encoded_password = 0x0000 + encoded_password = 0x0000 chars.each { |c| encoded_password ^= c } encoded_password ^= count encoded_password ^= 0xCE4B diff --git a/lib/axlsx/workbook/worksheet/sheet_view.rb b/lib/axlsx/workbook/worksheet/sheet_view.rb index 434f7b7a..dc41d01a 100644 --- a/lib/axlsx/workbook/worksheet/sheet_view.rb +++ b/lib/axlsx/workbook/worksheet/sheet_view.rb @@ -1,11 +1,9 @@ -# encoding: UTF-8 module Axlsx # View options for a worksheet. # # @note The recommended way to manage the sheet view is via Worksheet#sheet_view # @see Worksheet#sheet_view class SheetView - include Axlsx::OptionsParser include Axlsx::Accessors include Axlsx::SerializedAttributes @@ -30,8 +28,8 @@ module Axlsx # @option options [Integer] zoom_scale_normal Zoom Scale Normal View # @option options [Integer] zoom_scale_page_layout_view Zoom Scale Page Layout View # @option options [Integer] zoom_scale_sheet_layout_view Zoom Scale Page Break Preview - def initialize(options={}) - #defaults + def initialize(options = {}) + # defaults @color_id = @top_left_cell = @pane = nil @right_to_left = @show_formulas = @show_outline_symbols = @show_white_space = @tab_selected = @window_protection = false @default_grid_color = @show_grid_lines = @show_row_col_headers = @show_ruler = @show_zeros = true @@ -42,16 +40,15 @@ module Axlsx end boolean_attr_accessor :default_grid_color, :right_to_left, :show_formulas, :show_grid_lines, - :show_row_col_headers, :show_ruler, :show_white_space, :show_zeros, :tab_selected, :window_protection, :show_outline_symbols + :show_row_col_headers, :show_ruler, :show_white_space, :show_zeros, :tab_selected, :window_protection, :show_outline_symbols serializable_attributes :default_grid_color, :right_to_left, :show_formulas, :show_grid_lines, - :show_row_col_headers, :show_ruler, :show_white_space, :show_zeros, :tab_selected, :window_protection, :show_outline_symbols, - :zoom_scale_sheet_layout_view, :zoom_scale_page_layout_view, :zoom_scale_normal, :workbook_view_id, - :view, :top_left_cell, :color_id, :zoom_scale - + :show_row_col_headers, :show_ruler, :show_white_space, :show_zeros, :tab_selected, :window_protection, :show_outline_symbols, + :zoom_scale_sheet_layout_view, :zoom_scale_page_layout_view, :zoom_scale_normal, :workbook_view_id, + :view, :top_left_cell, :color_id, :zoom_scale # instance values that must be serialized as their own elements - e.g. not attributes. - CHILD_ELEMENTS = [ :pane, :selections ] + CHILD_ELEMENTS = [:pane, :selections] # The pane object for the sheet view # @return [Pane] @@ -66,11 +63,11 @@ module Axlsx # @return [Hash] attr_reader :selections - # + # # Color Id # Index to the color value for row/column - # text headings and gridlines. This is an - # 'index color value' (ICV) rather than + # text headings and gridlines. This is an + # 'index color value' (ICV) rather than # rgb value. # @see type # @return [Integer] @@ -78,18 +75,17 @@ module Axlsx attr_reader :color_id # Top Left Visible Cell - # Location of the top left visible cell Location + # Location of the top left visible cell Location # of the top left visible cell in the bottom right # pane (when in Left-to-Right mode). # @see type # @return [String] # default nil attr_reader :top_left_cell - - + # View Type # Indicates the view type. - # Options are + # Options are # * normal: Normal view # * page_break_preview: Page break preview # * page_layout: Page Layout View @@ -99,62 +95,59 @@ module Axlsx attr_reader :view # Workbook View Index - # Zero-based index of this workbook view, pointing + # Zero-based index of this workbook view, pointing # to a workbookView element in the bookViews collection. # @see type - # @return [Integer] + # @return [Integer] # default 0 attr_reader :workbook_view_id # Zoom Scale - # Window zoom magnification for current view + # Window zoom magnification for current view # representing percent values. This attribute - # is restricted to values ranging from 10 to 400. + # is restricted to values ranging from 10 to 400. # Horizontal & Vertical scale together. - # Current view can be Normal, Page Layout, or + # Current view can be Normal, Page Layout, or # Page Break Preview. # @see type - # @return [Integer] + # @return [Integer] # default 100 attr_reader :zoom_scale - # Zoom Scale Normal View - # Zoom magnification to use when in normal view, - # representing percent values. This attribute is - # restricted to values ranging from 10 to 400. + # Zoom magnification to use when in normal view, + # representing percent values. This attribute is + # restricted to values ranging from 10 to 400. # Horizontal & Vertical scale together. - # Applies for worksheets only; zero implies the + # Applies for worksheets only; zero implies the # automatic setting. # @see type - # @return [Integer] + # @return [Integer] # default 0 attr_reader :zoom_scale_normal - # Zoom Scale Page Layout View - # Zoom magnification to use when in page layout - # view, representing percent values. This attribute - # is restricted to values ranging from 10 to 400. + # Zoom magnification to use when in page layout + # view, representing percent values. This attribute + # is restricted to values ranging from 10 to 400. # Horizontal & Vertical scale together. - # Applies for worksheets only; zero implies + # Applies for worksheets only; zero implies # the automatic setting. # @see type - # @return [Integer] + # @return [Integer] # default 0 attr_reader :zoom_scale_page_layout_view - # Zoom Scale Page Break Preview - # Zoom magnification to use when in page break - # preview, representing percent values. This - # attribute is restricted to values ranging + # Zoom magnification to use when in page break + # preview, representing percent values. This + # attribute is restricted to values ranging # from 10 to 400. Horizontal & Vertical scale # together. - # Applies for worksheet only; zero implies + # Applies for worksheet only; zero implies # the automatic setting. # @see type - # @return [Integer] + # @return [Integer] # default 0 attr_reader :zoom_scale_sheet_layout_view @@ -172,7 +165,7 @@ module Axlsx # @see top_left_cell def top_left_cell=(v) cell = (v.class == Axlsx::Cell ? v.r_abs : v) - Axlsx::validate_string(cell) + Axlsx::validate_string(cell) @top_left_cell = cell end diff --git a/lib/axlsx/workbook/worksheet/table.rb b/lib/axlsx/workbook/worksheet/table.rb index 992486d2..4f446491 100644 --- a/lib/axlsx/workbook/worksheet/table.rb +++ b/lib/axlsx/workbook/worksheet/table.rb @@ -1,10 +1,8 @@ -# encoding: UTF-8 module Axlsx # Table # @note Worksheet#add_table is the recommended way to create tables for your worksheets. # @see README for examples class Table - include Axlsx::OptionsParser # Creates a new Table object @@ -12,13 +10,13 @@ module Axlsx # @param [Worksheet] sheet The sheet containing the table data. # @option options [Cell, String] name # @option options [TableStyle] style - def initialize(ref, sheet, options={}) + def initialize(ref, sheet, options = {}) @ref = ref @sheet = sheet @style = nil @sheet.workbook.tables << self @table_style_info = TableStyleInfo.new(options[:style_info]) if options[:style_info] - @name = "Table#{index+1}" + @name = "Table#{index + 1}" parse_options options yield self if block_given? end @@ -44,7 +42,7 @@ module Axlsx # The part name for this table # @return [String] def pn - "#{TABLE_PN % (index+1)}" + "#{TABLE_PN % (index + 1)}" end # The relationship id for this table. @@ -64,7 +62,7 @@ module Axlsx end end - # TableStyleInfo for the table. + # TableStyleInfo for the table. # initialization can be fed via the :style_info option def table_style_info @table_style_info ||= TableStyleInfo.new @@ -75,12 +73,12 @@ module Axlsx # @return [String] def to_xml_string(str = '') str << '<?xml version="1.0" encoding="UTF-8"?>' - str << ('<table xmlns="' << XML_NS << '" id="' << (index+1).to_s << '" name="' << @name << '" displayName="' << @name.gsub(/\s/,'_') << '" ') + str << ('<table xmlns="' << XML_NS << '" id="' << (index + 1).to_s << '" name="' << @name << '" displayName="' << @name.gsub(/\s/, '_') << '" ') str << ('ref="' << @ref << '" totalsRowShown="0">') str << ('<autoFilter ref="' << @ref << '"/>') str << ('<tableColumns count="' << header_cells.length.to_s << '">') - header_cells.each_with_index do |cell,index| - str << ('<tableColumn id ="' << (index+1).to_s << '" name="' << cell.clean_value << '"/>') + header_cells.each_with_index do |cell, index| + str << ('<tableColumn id ="' << (index + 1).to_s << '" name="' << cell.clean_value << '"/>') end str << '</tableColumns>' table_style_info.to_xml_string(str) diff --git a/lib/axlsx/workbook/worksheet/table_style_info.rb b/lib/axlsx/workbook/worksheet/table_style_info.rb index 22d85d41..537b2eea 100644 --- a/lib/axlsx/workbook/worksheet/table_style_info.rb +++ b/lib/axlsx/workbook/worksheet/table_style_info.rb @@ -1,5 +1,4 @@ module Axlsx - # The table style info class manages style attributes for defined tables in # a worksheet class TableStyleInfo @@ -15,7 +14,7 @@ module Axlsx # @option [Boolean] show_column_stripes indicates if column stripes should # be shown # @option [Boolean] show_row_stripes indicates if row stripes should be shown - # @option [String] name The name of the style to apply to your table. + # @option [String] name The name of the style to apply to your table. # Only predefined styles are currently supported. # @see Annex G. (normative) Predefined SpreadsheetML Style Definitions in part 1 of the specification. def initialize(options = {}) @@ -27,7 +26,7 @@ module Axlsx # boolean attributes for this object boolean_attr_accessor :show_first_column, :show_last_column, :show_row_stripes, :show_column_stripes serializable_attributes :show_first_column, :show_last_column, :show_row_stripes, :show_column_stripes, - :name + :name # Initialize all the values to false as Excel requires them to # explicitly be disabled or all will show. diff --git a/lib/axlsx/workbook/worksheet/tables.rb b/lib/axlsx/workbook/worksheet/tables.rb index d033212c..20ba4789 100644 --- a/lib/axlsx/workbook/worksheet/tables.rb +++ b/lib/axlsx/workbook/worksheet/tables.rb @@ -1,11 +1,10 @@ module Axlsx - # A simple, self serializing class for storing tables class Tables < SimpleTypedList - # creates a new Tables object def initialize(worksheet) raise ArgumentError, "you must provide a worksheet" unless worksheet.is_a?(Worksheet) + super Table @worksheet = worksheet end @@ -17,7 +16,8 @@ module Axlsx # returns the relationships required by this collection def relationships return [] if empty? - map{ |table| Relationship.new(table, TABLE_R, "../#{table.pn}") } + + map { |table| Relationship.new(table, TABLE_R, "../#{table.pn}") } end # renders the tables xml @@ -25,10 +25,10 @@ module Axlsx # @return [String] def to_xml_string(str = "") return if empty? + str << "<tableParts count='#{size}'>" each { |table| str << "<tablePart r:id='#{table.rId}'/>" } str << '</tableParts>' end end - end diff --git a/lib/axlsx/workbook/worksheet/worksheet.rb b/lib/axlsx/workbook/worksheet/worksheet.rb index dca483dc..d8451e9f 100644 --- a/lib/axlsx/workbook/worksheet/worksheet.rb +++ b/lib/axlsx/workbook/worksheet/worksheet.rb @@ -1,9 +1,6 @@ -# encoding: UTF-8 - require_relative "border_creator" module Axlsx - # The Worksheet class represents a worksheet in the workbook. class Worksheet include Axlsx::OptionsParser @@ -17,7 +14,7 @@ module Axlsx # @option options [Hash] print_options A hash containing print options for this worksheet. @see PrintOptions # @option options [Hash] header_footer A hash containing header/footer options for this worksheet. @see HeaderFooter # @option options [Boolean] show_gridlines indicates if gridlines should be shown for this sheet. - def initialize(wb, options={}) + def initialize(wb, options = {}) self.workbook = wb @sheet_protection = nil initialize_page_options(options) @@ -43,7 +40,7 @@ module Axlsx # The name of the worksheet # @return [String] def name - @name ||= "Sheet" + (index+1).to_s + @name ||= "Sheet" + (index + 1).to_s end # Specifies the visible state of this sheet. Allowed states are @@ -102,13 +99,13 @@ module Axlsx # The tables in this worksheet # @return [Array] of Table def tables - @tables ||= Tables.new self + @tables ||= Tables.new self end # The pivot tables in this worksheet # @return [Array] of Table def pivot_tables - @pivot_tables ||= PivotTables.new self + @pivot_tables ||= PivotTables.new self end # A collection of column breaks added to this worksheet @@ -172,10 +169,10 @@ module Axlsx # @see #page_setup def fit_to_page? return false unless Axlsx.instance_values_for(self).keys.include?('page_setup') + page_setup.fit_to_page? end - # Column info for the sheet # @return [SimpleTypedList] def column_info @@ -311,7 +308,7 @@ module Axlsx # @param [String] name def name=(name) validate_sheet_name name - @name=Axlsx::coder.encode(name) + @name = Axlsx::coder.encode(name) end # The auto filter range for the worksheet @@ -329,13 +326,13 @@ module Axlsx # The part name of this worksheet # @return [String] def pn - "#{WORKSHEET_PN % (index+1)}" + "#{WORKSHEET_PN % (index + 1)}" end # The relationship part name of this worksheet # @return [String] def rels_pn - "#{WORKSHEET_RELS_PN % (index+1)}" + "#{WORKSHEET_RELS_PN % (index + 1)}" end # The relationship id of this worksheet. @@ -412,7 +409,7 @@ module Axlsx # sign as formula (default) or as simple string. # Allowing user generated data to be interpreted as formulas can be dangerous # (see https://www.owasp.org/index.php/CSV_Injection for details). - def add_row(values=[], options={}) + def add_row(values = [], options = {}) row = Row.new(self, values, options) update_column_info row, options.delete(:widths) yield row if block_given? @@ -432,7 +429,7 @@ module Axlsx # @see ConditionalFormattingRule#initialize # @see file:examples/example_conditional_formatting.rb def add_conditional_formatting(cells, rules) - cf = ConditionalFormatting.new( :sqref => cells ) + cf = ConditionalFormatting.new(:sqref => cells) cf.add_rules rules conditional_formattings << cf conditional_formattings @@ -453,7 +450,7 @@ module Axlsx # @param [Hash] options for the hyperlink # @see WorksheetHyperlink for a list of options # @return [WorksheetHyperlink] - def add_hyperlink(options={}) + def add_hyperlink(options = {}) hyperlinks.add(options) end @@ -470,33 +467,33 @@ module Axlsx # @see Bar3DChart # @see Line3DChart # @see README for examples - def add_chart(chart_type, options={}) + def add_chart(chart_type, options = {}) chart = worksheet_drawing.add_chart(chart_type, options) yield chart if block_given? chart end # needs documentation - def add_table(ref, options={}) + def add_table(ref, options = {}) tables << Table.new(ref, self, options) yield tables.last if block_given? tables.last end - def add_pivot_table(ref, range, options={}) + def add_pivot_table(ref, range, options = {}) pivot_tables << PivotTable.new(ref, range, self, options) yield pivot_tables.last if block_given? pivot_tables.last end # Shortcut to worsksheet_comments#add_comment - def add_comment(options={}) + def add_comment(options = {}) worksheet_comments.add_comment(options) end # Adds a media item to the worksheets drawing # @option [Hash] options options passed to drawing.add_image - def add_image(options={}) + def add_image(options = {}) image = worksheet_drawing.add_image(options) yield image if block_given? image @@ -510,10 +507,10 @@ module Axlsx def add_page_break(cell) DataTypeValidator.validate :worksheet_page_break, [String, Cell], cell column_index, row_index = if cell.is_a?(String) - Axlsx.name_to_indices(cell) - else - cell.pos - end + Axlsx.name_to_indices(cell) + else + cell.pos + end if column_index > 0 col_breaks.add_break(:id => column_index) end @@ -530,6 +527,7 @@ module Axlsx def column_widths(*widths) widths.each_with_index do |value, index| next if value == nil + Axlsx::validate_unsigned_numeric(value) unless value == nil find_or_create_column_info(index).width = value end @@ -543,7 +541,7 @@ module Axlsx # @note You can also specify the style for specific columns in the call to add_row by using an array for the :styles option # @see Worksheet#add_row # @see README.md for an example - def col_style(index, style, options={}) + def col_style(index, style, options = {}) offset = options.delete(:row_offset) || 0 cells = @rows[(offset..-1)].map { |row| row[index] }.flatten.compact cells.each { |cell| cell.style = style } @@ -557,7 +555,7 @@ module Axlsx # @note You can also specify the style in the add_row call # @see Worksheet#add_row # @see README.md for an example - def row_style(index, style, options={}) + def row_style(index, style, options = {}) offset = options.delete(:col_offset) || 0 cells = cols[(offset..-1)].map { |column| column[index] }.flatten.compact cells.each { |cell| cell.style = style } @@ -587,7 +585,7 @@ module Axlsx # Set the style for cells in a specific column # @param [String|Array] cell references # @param [Hash|Array|Symbol] border options - def add_border(cell_refs, options=nil) + def add_border(cell_refs, options = nil) if options.is_a?(Hash) border_edges = options[:edges] border_style = options[:style] @@ -610,7 +608,7 @@ module Axlsx end # Returns a sheet node serialization for this sheet in the workbook. - def to_sheet_node_xml_string(str='') + def to_sheet_node_xml_string(str = '') add_autofilter_defined_name_to_workbook str << '<sheet ' serialized_attributes str @@ -621,7 +619,7 @@ module Axlsx # Serializes the worksheet object to an xml string # This intentionally does not use nokogiri for performance reasons # @return [String] - def to_xml_string str='' + def to_xml_string str = '' add_autofilter_defined_name_to_workbook auto_filter.apply if auto_filter.range str << '<?xml version="1.0" encoding="UTF-8"?>' @@ -650,7 +648,7 @@ module Axlsx def [](cell_def) return rows[cell_def] if cell_def.is_a?(Integer) - parts = cell_def.split(':').map{ |part| name_to_cell part } + parts = cell_def.split(':').map { |part| name_to_cell part } if parts.size == 1 parts.first @@ -724,7 +722,7 @@ module Axlsx end def outline(collection, range, level = 1, collapsed = true) - range.each do |index| + range.each do |index| unless (item = collection[index]).nil? item.outline_level = level item.hidden = collapsed @@ -737,9 +735,11 @@ module Axlsx DataTypeValidator.validate :worksheet_name, String, name # ignore first character (BOM) after encoding to utf16 because Excel does so, too. raise ArgumentError, (ERR_SHEET_NAME_EMPTY) if name.empty? + character_length = name.encode("utf-16")[1..-1].encode("utf-16").bytesize / 2 raise ArgumentError, (ERR_SHEET_NAME_TOO_LONG % name) if character_length > WORKSHEET_MAX_NAME_LENGTH raise ArgumentError, (ERR_SHEET_NAME_CHARACTER_FORBIDDEN % name) if WORKSHEET_NAME_FORBIDDEN_CHARS.any? { |char| name.include? char } + name = Axlsx::coder.encode(name) sheet_names = @workbook.worksheets.reject { |s| s == self }.map { |s| s.name } raise ArgumentError, (ERR_DUPLICATE_SHEET_NAME % name) if sheet_names.include?(name) @@ -794,7 +794,6 @@ module Axlsx @merged_cells ||= MergedCells.new self end - # Helper method for parsingout the root node for worksheet # @return [String] def worksheet_node @@ -833,8 +832,8 @@ module Axlsx def add_autofilter_defined_name_to_workbook return if !auto_filter.range + workbook.add_defined_name auto_filter.defined_name, name: '_xlnm._FilterDatabase', local_sheet_id: index, hidden: 1 end - end end diff --git a/lib/axlsx/workbook/worksheet/worksheet_comments.rb b/lib/axlsx/workbook/worksheet/worksheet_comments.rb index f9e4c8cd..29ea6fc8 100644 --- a/lib/axlsx/workbook/worksheet/worksheet_comments.rb +++ b/lib/axlsx/workbook/worksheet/worksheet_comments.rb @@ -1,13 +1,12 @@ module Axlsx - # A wraper class for comments that defines its on worksheet # serailization class WorksheetComments - # Creates a new WorksheetComments object # param [Worksheet] worksheet The worksheet comments in thes object belong to def initialize(worksheet) raise ArugumentError, 'You must provide a worksheet' unless worksheet.is_a?(Worksheet) + @worksheet = worksheet end @@ -22,18 +21,18 @@ module Axlsx # Adds a comment # @param [Hash] options # @see Comments#add_comment - def add_comment(options={}) + def add_comment(options = {}) comments.add_comment(options) - end + end # The relationships defined by this objects comments collection # @return [Relationships] def relationships return [] unless has_comments? + comments.relationships end - # Helper method to tell us if there are comments in the comments collection # @return [Boolean] def has_comments? @@ -44,7 +43,7 @@ module Axlsx # @see Relationship#Id # @return [String] def drawing_rId - comments.relationships.find{ |r| r.Type == VML_DRAWING_R }.Id + comments.relationships.find { |r| r.Type == VML_DRAWING_R }.Id end # Seraalize the object @@ -52,6 +51,7 @@ module Axlsx # @return [String] def to_xml_string(str = '') return unless has_comments? + str << "<legacyDrawing r:id='#{drawing_rId}' />" end end diff --git a/lib/axlsx/workbook/worksheet/worksheet_drawing.rb b/lib/axlsx/workbook/worksheet/worksheet_drawing.rb index ae03ac0f..c2819393 100644 --- a/lib/axlsx/workbook/worksheet/worksheet_drawing.rb +++ b/lib/axlsx/workbook/worksheet/worksheet_drawing.rb @@ -1,15 +1,14 @@ module Axlsx - # This is a utility class for serialing the drawing node in a # worksheet. Drawing objects have their own serialization that exports # a drawing document. This is only for the single node in the # worksheet class WorksheetDrawing - # Creates a new WorksheetDrawing # @param [Worksheet] worksheet def initialize(worksheet) raise ArgumentError, 'you must provide a worksheet' unless worksheet.is_a?(Worksheet) + @worksheet = worksheet @drawing = nil end @@ -45,6 +44,7 @@ module Axlsx # @return [Relationship] def relationship return unless has_drawing? + Relationship.new(self, DRAWING_R, "../#{drawing.pn}") end @@ -52,6 +52,7 @@ module Axlsx # @param [String] str def to_xml_string(str = '') return unless has_drawing? + str << "<drawing r:id='#{relationship.Id}'/>" end end diff --git a/lib/axlsx/workbook/worksheet/worksheet_hyperlink.rb b/lib/axlsx/workbook/worksheet/worksheet_hyperlink.rb index 2a241287..60615f1c 100644 --- a/lib/axlsx/workbook/worksheet/worksheet_hyperlink.rb +++ b/lib/axlsx/workbook/worksheet/worksheet_hyperlink.rb @@ -1,8 +1,6 @@ module Axlsx - # A worksheet hyperlink object. Note that this is not the same as a drawing hyperlink object. class WorksheetHyperlink - include Axlsx::OptionsParser include Axlsx::Accessors include Axlsx::SerializedAttributes @@ -15,7 +13,7 @@ module Axlsx # @option [String] tooltip The tip to display when the user positions the mouse cursor over this hyperlink # @option [Symbol] target This is :external by default. If you set it to anything else, the location is interpreted to be the current workbook. # @option [String|Cell] ref The location of this hyperlink in the worksheet - def initialize(worksheet, options={}) + def initialize(worksheet, options = {}) DataTypeValidator.validate "Hyperlink.worksheet", [Worksheet], worksheet @worksheet = worksheet @target = :external @@ -27,7 +25,7 @@ module Axlsx serializable_attributes :display, :tooltip, :ref - #Cell location of hyperlink on worksheet. + # Cell location of hyperlink on worksheet. # @return [String] attr_reader :ref @@ -51,13 +49,14 @@ module Axlsx # @return [Relationship] def relationship return unless @target == :external + Relationship.new(self, HYPERLINK_R, location, :target_mode => :External) end # Seralize the object # @param [String] str # @return [String] - def to_xml_string(str='') + def to_xml_string(str = '') str << '<hyperlink ' serialized_attributes str, location_or_id str << '/>' @@ -68,7 +67,7 @@ module Axlsx # r:id should only be specified for external targets. # @return [Hash] def location_or_id - @target == :external ? { :"r:id" => relationship.Id } : { :location => Axlsx::coder.encode(location) } + @target == :external ? { :"r:id" => relationship.Id } : { :location => Axlsx::coder.encode(location) } end end end diff --git a/lib/axlsx/workbook/worksheet/worksheet_hyperlinks.rb b/lib/axlsx/workbook/worksheet/worksheet_hyperlinks.rb index a242f0f8..44c6125a 100644 --- a/lib/axlsx/workbook/worksheet/worksheet_hyperlinks.rb +++ b/lib/axlsx/workbook/worksheet/worksheet_hyperlinks.rb @@ -1,8 +1,6 @@ module Axlsx - - #A collection of hyperlink objects for a worksheet + # A collection of hyperlink objects for a worksheet class WorksheetHyperlinks < SimpleTypedList - # Creates a new Hyperlinks collection # @param [Worksheet] worksheet the worksheet that owns these hyperlinks def initialize(worksheet) @@ -23,13 +21,15 @@ module Axlsx # @return Array def relationships return [] if empty? + map { |hyperlink| hyperlink.relationship } end # seralize the collection of hyperlinks # @return [String] - def to_xml_string(str='') + def to_xml_string(str = '') return if empty? + str << '<hyperlinks>' each { |hyperlink| hyperlink.to_xml_string(str) } str << '</hyperlinks>' diff --git a/lib/caxlsx.rb b/lib/caxlsx.rb index a82d49fb..047ed28f 100644 --- a/lib/caxlsx.rb +++ b/lib/caxlsx.rb @@ -1,2 +1 @@ -# encoding: UTF-8 require 'axlsx.rb' |
