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/axlsx/workbook/worksheet | |
| 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/axlsx/workbook/worksheet')
56 files changed, 515 insertions, 557 deletions
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>' |
