Django / python以及xlwt语言环境格式的问题

时间:2014-06-18 23:48:24

标签: python django excel xlwt

我正在使用django-excel-view,它使用django-excel-response,后者又使用xlwt。我有一个场景,用户可以切换区域设置,让他们查看带有标准小数点的浮点数,或者在某些语言中查看逗号小数点。

当将视图导出为带有标准小数点区域设置的xls时,它可以正常工作,但使用逗号小数使xls文件将float存储为文本,并在数字前添加撇号(例如'123,45)。我有一种感觉,ExcelResponse(https://djangosnippets.org/snippets/1151/)没有正确处理浮动(参见代码片段的第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格式。

2 个答案:

答案 0 :(得分:4)

  

我有一个场景,用户可以切换区域设置,让他们查看带有标准小数点的浮点数,或者用某些语言查看逗号小数点。

这里需要注意的重要一点是,语言环境的千位/小数分隔符是Windows设置而不是Excel设置。它在控制面板/区域和语言选项/格式或类似设置中设置。

因此,如果在一个区域设置中,数字格式在Excel中显示为1,234.56,而在另一个区域设置中,在两种情况下显示为1.234,56 格式存储在Excel中作为美国风格:0,000.00

因此,在使用xlwt或任何其他电子表格编写模块时,您应该使用美式样式格式选项(逗号为千和。十进制)。然后,它将根据Windows设置显示在用户区域设置中。

答案 1 :(得分:2)

您可以使用easyxf,但也可以使用xwlt样式,如:

# You can change the format to more or less decimals
decimal_style.num_format_str = '0.0000'  


sheet.write(0, 0, 3.18526119, decimal_style)  # Example to write
sheet.write(0, 1, 1.11, decimal_style)  # Another example

如果您想使用easyxf,可以执行以下操作:

decimal_style = easyxf(num_format_str='0.00')
sheet.write(0, 0, '999.99', decimal_style)

您可以查看此示例以获取更多信息Python: Writing xlwt files