From eba6b93bd0a72670fb7af7d68e1ea0351823ed23 Mon Sep 17 00:00:00 2001 From: Leigh Dodds Date: Tue, 7 Nov 2023 14:43:39 +0000 Subject: [PATCH] Fix number formatting with empty cells --- lib/roo/excelx/cell/number.rb | 3 ++ spec/lib/roo/excelx/cell/number_spec.rb | 55 +++++++++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 spec/lib/roo/excelx/cell/number_spec.rb diff --git a/lib/roo/excelx/cell/number.rb b/lib/roo/excelx/cell/number.rb index 5cdec5eb..bb616c58 100644 --- a/lib/roo/excelx/cell/number.rb +++ b/lib/roo/excelx/cell/number.rb @@ -18,6 +18,8 @@ def initialize(value, formula, excelx_type, style, link, coordinate) def create_numeric(number) return number if Excelx::ERROR_VALUES.include?(number) + return nil if (number.nil? || number == "") + case @format when /%/ Float(number) @@ -30,6 +32,7 @@ def create_numeric(number) def formatted_value return @cell_value if Excelx::ERROR_VALUES.include?(@cell_value) + return '' if (@cell_value.nil? || @cell_value == "") formatter = generate_formatter(@format) if formatter.is_a? Proc diff --git a/spec/lib/roo/excelx/cell/number_spec.rb b/spec/lib/roo/excelx/cell/number_spec.rb new file mode 100644 index 00000000..bf92013f --- /dev/null +++ b/spec/lib/roo/excelx/cell/number_spec.rb @@ -0,0 +1,55 @@ +require 'spec_helper' + +RSpec.describe Roo::Excelx::Cell::Number do + + describe '#initialize' do + let(:formula) { nil } + let(:excelx_type) { [:numeric_or_formula, format] } + let(:format) { "#,##0.00" } + let(:style) { 1 } + let(:link) { nil } + let(:coordinate) { [1,1] } + + let(:number) { Roo::Excelx::Cell::Number.new(value, formula, excelx_type, style, link, coordinate)} + + context 'with an actual value' do + let(:value) { 0.1 } + it 'creates the object and parses the value' do + expect(number.value).to eq 0.1 + end + end + + context 'with an empty value' do + let(:value) { "" } + it 'creates the object with a nil value' do + expect(number.value).to eq nil + end + end + end + + describe '#formatted_value' do + let(:formula) { nil } + let(:excelx_type) { [:numeric_or_formula, format] } + let(:format) { "#,##0.00" } + let(:style) { 1 } + let(:link) { nil } + let(:coordinate) { [1,1] } + + let(:number) { Roo::Excelx::Cell::Number.new(value, formula, excelx_type, style, link, coordinate)} + + context 'with an actual value' do + let(:value) { 0.1 } + it 'creates the object and parses the value' do + expect(number.formatted_value).to eq '0.10' + end + end + + context 'with an empty value' do + let(:value) { "" } + it 'creates the object with a nil value' do + expect(number.formatted_value).to eq '' + end + end + + end +end