首页 > 解决方案 > 如何使用 Python 在 Excel 的行尾动态添加总计?

问题描述

for item in results:    
    titleformat = book.add_format({'bold': True, 'align': 'center'})
    center      = book.add_format({'align' : 'center'})

    usersheet.write(0, 0, "#"             , titleformat)
    usersheet.write(0, 1, "User"          , titleformat)
    usersheet.write(0, 2, "Group"         , titleformat)
    usersheet.write(0, 3, "SVN Commits"   , titleformat)
    usersheet.write(0, 4, "GIT Commits"   , titleformat)
    usersheet.write(0, 5, "GITLAB Commits", titleformat)
    usersheet.write(0, 6, "Gerrit Review" , titleformat)
.
.
.
.
    #### set column widths
    usersheet.set_column(userrowno, 0, 5)
    for i in range(1,26):
        usersheet.set_column(userrowno, i, 20)

    
    userrowno = userrowno + 1

通过这段代码,我们动态地创建了两个 Excel 工作表。但是,由于数据总是在变化,因此每个数据的最后一行看起来都不同。如何在 Python 中动态写入每列末尾的总数据?图片中的 TOTAL 文本应在代码中生成为通用文本,并应写在每列的末尾。

标签: javascriptpythonexcel-formulapython-3.6

解决方案


最简单的方法是将其读入 pandas 中的数据框,对列求和,然后用标题重写工作表。

import pandas as pd

df = pd.read_excel(path_to_sheet)
df.loc["Total"] = df.sum()
writer = pd.ExcelWriter(path_where_you_want)

...do what you're doing above with pandas writer object...

df.to_excel(writer)

https://pandas.pydata.org/docs/reference/api/pandas.ExcelWriter.html

https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_excel.html

编辑:如果您有非数字列,您可能需要设置索引


推荐阅读