Django/python与xlwt本地化格式问题

4 投票
2 回答
1512 浏览
提问于 2025-04-18 10:18

我正在使用django-excel-view,这个工具又依赖于django-excel-response,而django-excel-response又使用了xlwt。我的情况是,用户可以切换语言设置,这样他们就可以选择用标准的小数点或者在某些语言中用逗号作为小数点来查看数字。

当我用标准小数点的语言设置导出xls文件时,一切都很正常,但如果使用逗号作为小数点,xls文件就会把浮点数当作文本来处理,并在数字前加上一个撇号(比如 '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 个回答

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

4

我有一个情况,用户可以切换语言环境,这样他们就能看到浮点数(小数)用标准的点号表示,或者在某些语言中用逗号表示。

这里需要注意的是,千位分隔符和小数点符号是Windows的设置,而不是Excel的设置。这个设置可以在控制面板的区域和语言选项里找到,通常在格式选项中。

所以,如果在一个语言环境下,Excel中数字的显示格式是 1,234.56,而在另一个语言环境下显示为 1.234,56,在这两种情况下,Excel中存储的格式都是美国的样式:0,000.00

因此,当使用xlwt或其他电子表格写入模块时,你应该使用美国的格式选项(千位用逗号,小数用点)。这样,数字就会根据用户的Windows设置在他们的语言环境中正确显示。

撰写回答