Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix xlsx parsing of empty cells with no formatting #591

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 15 additions & 3 deletions lib/roo/excelx/cell/number.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,26 @@ def create_numeric(number)
return number if Excelx::ERROR_VALUES.include?(number)
case @format
when /%/
Float(number)
cast_float(number)
when /\.0/
Float(number)
cast_float(number)
else
(number.include?('.') || (/\A[-+]?\d+E[-+]?\d+\z/i =~ number)) ? Float(number) : Integer(number, 10)
(number.include?('.') || (/\A[-+]?\d+E[-+]?\d+\z/i =~ number)) ? cast_float(number) : cast_int(number, 10)
end
end

def cast_float(number)
return 0.0 if number == ''

Float(number)
end

def cast_int(number, base = 10)
return 0 if number == ''

Integer(number, base)
end

def formatted_value
return @cell_value if Excelx::ERROR_VALUES.include?(@cell_value)

Expand Down
9 changes: 9 additions & 0 deletions spec/lib/roo/excelx_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -616,6 +616,15 @@
end
end

describe 'empty value cells with no format' do
let(:path) { 'test/files/empty_numeric_cell.xlsx' }

it 'returns 0 for empty numeric cells' do
expect(subject.excelx_value(3, 2)).to eq('')
expect(subject.cell(3, 2)).to eq(0)
end
end

describe 'opening a file with a chart sheet' do
let(:path) { 'test/files/chart_sheet.xlsx' }
it 'should not raise' do
Expand Down
5 changes: 5 additions & 0 deletions test/excelx/cell/test_number.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@ def test_integer
assert_kind_of(Integer, cell.value)
end

def test_blank
cell = Roo::Excelx::Cell::Number.new '', nil, ['0'], nil, nil, nil
assert_kind_of(Integer, cell.value)
end

def test_scientific_notation
cell = Roo::Excelx::Cell::Number.new '1.2E-3', nil, ['0'], nil, nil, nil
assert_kind_of(Float, cell.value)
Expand Down
Binary file added test/files/empty_numeric_cell.xlsx
Binary file not shown.