javascript - 如何使用 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 文本应在代码中生成为通用文本,并应写在每列的末尾。
解决方案
最简单的方法是将其读入 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
编辑:如果您有非数字列,您可能需要设置索引
推荐阅读
- r - 在评估表达式时解析 R 中的错误
- python - 比较特征提取器(或比较对齐的图像)
- javascript - 将 _body 内容(字符串)转换为 arrayBuffer
- php - 使用 PHP 将项目循环并计数到多维数组中
- javascript - D3js 饼图未显示在本地主机上
- python - Python 3.7.2 ModuleNotFoundError:没有名为 pysqlite2 的模块
- java - 汇总 ArrayList 中的所有条目
- c++ - int' to float' 需要缩小转换
- java - 无法使用具有多个步骤文件的 Cucumber 配置 Spring Boot
- python - 不明白 os.path.dirname() 是如何工作的