【发布时间】:2014-08-09 09:48:51
【问题描述】:
我正在使用 django-excel-view,它使用 django-excel-response,而后者又使用 xlwt。我有一个场景,用户可以切换区域设置,让他们查看带有标准小数点的浮点数,或者在某些语言中使用逗号小数点。
当将视图导出为具有标准小数点语言环境的 xls 时,它可以正常工作,但使用逗号小数会使 xls 文件将浮点数存储为文本并在数字前添加撇号(例如 '123,45)。我感觉 ExcelResponse (https://djangosnippets.org/snippets/1151/) 没有正确处理浮点数(参见 sn-p 之后的第 43 行)。
什么是正确的 xlwt 样式来申请使用逗号小数正确保存的 xls,以及检查一个值是否是逗号小数并且应该应用该样式的好方法是什么?换句话说:
styles = {'datetime': xlwt.easyxf(num_format_str='yyyy-mm-dd hh:mm:ss'),
'date': xlwt.easyxf(num_format_str='yyyy-mm-dd'),
'time': xlwt.easyxf(num_format_str='hh:mm:ss'),
'default': xlwt.Style.default_style,
'comma_decimal': xlwt.easyxf('????????')}
for rowx, row in enumerate(data):
for colx, value in enumerate(row):
if isinstance(value, datetime.datetime):
cell_style = styles['datetime']
elif isinstance(value, datetime.date):
cell_style = styles['date']
elif isinstance(value, datetime.time):
cell_style = styles['time']
elif isinstance(value, ?????????????):
cell_style = styles['comma_decimal']
else:
cell_style = styles['default']
sheet.write(rowx, colx, value, style=cell_style)
解决方案:
我最终在 django-excel-response 中添加了一个额外的检查,它对逗号浮点值进行一些正则表达式检查(它们应该是由 django 语言环境添加的),然后用小数点替换逗号。
elif (re.compile("^[0-9]+([,][0-9]+)?$")).match(u"{}".format(value)):
value = float(value.replace(',', '.'))
jmcnamara 帮助我指出了这个方向,而不是搞乱语言环境和 xlwt 格式。
【问题讨论】: