首页 > 解决方案 > py3o.template 如何以正确的格式呈现“值”字段

问题描述

我正在尝试使用 python(jupyter notebook)和库 py3o.template 创建自动 ODT 文档(LibreOffice writer)。

所有精细渲染到 ODT,但我无法将正确格式化的值渲染到最终文档。到目前为止,我在 ODT 模板中尝试了以下调整,但没有成功:

如果我不进行任何配置,最终文档将以文本形式获取值,但完全未格式化(十进制精度,千位分隔符)。如果我尝试调整上述选项,那么它只会得到“零”

py3o 库提到了一种(已弃用)使用特殊函数(例如 format_currency)格式化字段的方法,但这些函数会将“数字”转换为格式化的“字符串”。我设法使用它们,但这不是理想的解决方案。

我想要的是能够在最终的 odt 文档中将数字合并为具有正确格式(千位分隔符和 2 位小数精度)的数字。有什么建议么 ??

这是我的 python/jupyter 代码:

# example for StackOverflow
# classes to create objects -> since py3o.Template demands fields callable by ".field_name"
class Item(object):
    pass

class df2obj(object):
    def __init__(self, c1_txt, c2_txt, c3_int, c4_txt, c5_val):
        self.c1_txt = c1_txt
        self.c2_txt = c2_txt
        self.c3_int = c3_int
        self.c4_txt = c4_txt
        self.c5_val = c5_val

# example data
client_name = 'Hipotetical Client'
client_id = '06198111'

table_data = {'c1_txt':['06198111', '06198111', '06198111', '06198111', '06198111'],
        'c2_txt':['2019', '2020', '2018', '2019', '2021'],
        'c3_int':[1, 5, 6, 7, 2],
        'c4_txt':['blue', 'red', 'black', 'white', 'brown'],
        'c5_val':[8759642.91927, 28389495.4399999, 21553875, 999613.2, 64]}
df = pd.DataFrame(table_data)

# adjusting data to be callable by ".field" (as required by py3o.Template)
# general client data
cli = Item()
cli.id = client_id
cli.name = client_name
# table data
table = [df2obj(**kwargs) for kwargs in df.to_dict(orient='records')]


from py3o.template import Template 
out_file = 'report_example.odt' 
t = Template("my_py3o_model.odt", out_file) 
template_data = dict(cli=cli, table=table) 
t.render(template_data)

标签: pythonpandastemplatesjupyter-notebooklibreoffice-writer

解决方案


推荐阅读