简体   繁体   English

如何使用 openpyxl 在特定列上写入总计

[英]How to write totals on a particular columns using openpyxl

I have an excel spreadsheet with multiple columns.我有一个包含多列的 Excel 电子表格。 How can I iterate through particular columns and create a sum on the bottom.如何遍历特定列并在底部创建总和。 Number of rows is dynamic.行数是动态的。

在此处输入图片说明

A simple but nice solution:一个简单但不错的解决方案:

def sum_col(ws, col, col_top=2, tight=False):
    col_len = len(ws[col])
    if tight:
        col_len -= next(i for i, x in enumerate(reversed(ws[col])) if x.value is not None)
    ws[f'{col}{col_len + 1}'] = f'=SUM({col}{col_top}:{col}{col_len})'

If your example data sums.xlsx would look like:如果您的示例数据sums.xlsx如下所示:

"a",1,"b",2,"c"
"d",2,"e",2,"f"
"g",3,   , ,"h"
"i", ,   , ,

Then this:然后这个:

from openpyxl import load_workbook


def sum_col(ws, col, col_top=2, tight=False):
    col_len = len(ws[col])
    if tight:
        col_len -= next(i for i, x in enumerate(reversed(ws[col])) if x.value is not None)
    ws[f'{col}{col_len + 1}'] = f'=SUM({col}{col_top}:{col}{col_len})'


wb = load_workbook('sums.xlsx')
ws = wb.active

sum_col(ws, 'B', col_top=1)
sum_col(ws, 'D', col_top=1, tight=True)
wb.save('changed_sums.xlsx')

Would result in:会导致:

"a",1,"b",2,"c"
"d",2,"e",2,"f"
"g",3,   ,4,"h"
"i", ,   , ,
   ,6,   , ,

(with 6 and 4 being the results of SUMs of course) (当然, 64是 SUM 的结果)

Note that col_top=1 is passed because the function assumes there's a one line header (which there isn't in the example).请注意,传递col_top=1是因为该函数假设有一个单行标题(示例中没有)。 And the tight parameter causes the script to find the actual end of the column (first non-None cell) instead of what openpyxl thinks is the end of the column (which is basically just the number of rows with data).并且tight参数使脚本找到列的实际结尾(第一个非 None 单元格),而不是openpyxl认为是列的结尾(基本上只是包含数据的行数)。

This one does the trick.这个可以解决问题。 But if someone know better way, please provide.但如果有人知道更好的方法,请提供。

from openpyxl import load_workbook
from xlsxwriter.utility import xl_rowcol_to_cell

# Get the number of rows 
df_len = len(df.index)

# list of column numbers that need to show sum at the bottom
col = [0, 2]

# iterating through those columns
for column in col:
    # Determine where we will place the formula
    cell_location = xl_rowcol_to_cell(df_len + 1, column)  # xl_rowcol_to_cell(RowNumber, ColumnNumber)
    # Get the range to use for the sum formula
    start_range = xl_rowcol_to_cell(1, column)  # row 1 (start from 0!) and  column 6 and so on
    end_range = xl_rowcol_to_cell(df_len, column)
    # Construct and write the formula
    formula = "=SUM({:s}:{:s})".format(start_range, end_range)  # {:s} substituted with "start_range" and "end_range" accordingly
    cell = ws[cell_location]
    cell.value = formula

wb.save('changed_sums.xlsx')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM