Skip to content

Instantly share code, notes, and snippets.

@zsoldosp
Last active August 29, 2015 14:17
Show Gist options
  • Save zsoldosp/9f14423a00562b0d219c to your computer and use it in GitHub Desktop.
Save zsoldosp/9f14423a00562b0d219c to your computer and use it in GitHub Desktop.
openpyxl decimal/float formatting problem
from openpyxl.workbook import Workbook
from openpyxl.writer.excel import save_virtual_workbook, save_workbook
from openpyxl.reader.excel import load_workbook
from decimal import Decimal
import tempfile
import os
def get_filepath(name):
fh, path = tempfile.mkstemp(prefix=name, suffix='.xlsx')
os.close(fh)
return path
def unoptimized(decnum):
wb = Workbook()
ws = wb.get_active_sheet()
cell = ws.cell(row=1, column=1)
cell.value = float(decnum)
# FIX: the below works in 2.1.0
# cell.set_explicit_value(value='%.2f' % value, data_type=cell.TYPE_NUMERIC)
filepath = get_filepath('optimized')
save_workbook(wb, filepath)
return filepath
def optimized(decnum):
wb = Workbook(optimized_write=True)
ws = wb.create_sheet()
ws.append([float(decnum)])
filepath = get_filepath('unoptimized')
wb.save(filepath)
return filepath
def readnum(filepath):
wb = load_workbook(filepath)
ws = wb.get_active_sheet()
val = ws.rows[0][0].value
print val
return val
def assert_equal(expected, actual):
assert expected == actual, 'Expected %r, got %r' % (expected, actual)
def assert_float_equal(expected, actual):
assert_equal(type(expected), type(actual))
assert_equal(expected, actual)
if __name__ == '__main__':
input_ = 80.0
assert_float_equal(input_, readnum(optimized(input_)))
assert_float_equal(input_, readnum(unoptimized(input_)))
ipdb==0.8
ipython==2.4.1
jdcal==1.0
lxml==3.3.4
openpyxl==2.1.0
py==1.4.26
pytest==2.5.2
ipdb==0.8
ipython==2.4.1
jdcal==1.0
lxml==3.3.4
openpyxl==2.0.5
py==1.4.26
pytest==2.5.2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment