将变量输入字符串的Python函数

问题描述 投票:0回答:1

我已使用xlsxwriter将pandas df输出到excel文件中。我正在尝试在顶部创建总计行。为此,我正在尝试创建一个函数,该函数根据我选择的列动态填充总数。

这里是我打算做的一个例子:

worksheet.write_formula('G4', '=SUM(G4:G21)')
#G4 = Where total should be placed

我需要这是一个函数,因为行数可以更改(求和范围应该是动态的),并且我希望有一种简便的方法将此公式应用于各个列。

因此,我提出了以下内容:

def get_totals(column):
    start_row = '4' #row which the totals will be on
    row_count = str(tl_report.shape[0]) #number of rows in the table so I can sum up every row.  
    return (worksheet.write_formula(str(column+start_row),"'=SUM("+str(column+start_row)+":"+str(column+row_count)+")'") )


运行get_totals(“ G”)时,其结果仅为0。我怀疑它与我必须应用的STR运算符有关,因为该运算符在公式中添加了单引号,因此错误地呈现了它。

但是由于无法明显地连接INT,所以我无法删除str运算符?

[也许我正在编写所有错误的代码,这是python的新功能,不胜感激。

谢谢!

python excel function xlsxwriter
1个回答
0
投票

几乎在所有情况下,XlsxWriter方法都支持两种表示形式来指定单元格的位置:行-列表示法和A1表示法。

行表示法对行和列均使用从零开始的索引,而A1表示法则使用列字母和基于1的行的标准Excel字母数字序列。例如:

(6, 2)      # Row-column notation.
('C7')      # The same cell in A1 notation.

因此,对于您的情况,您可以执行以下操作并以编程方式设置行列值(您可能必须调整-1才能获得零索引):

worksheet.write_formula(start_row, start_column, '=SUM(G4:G21)')

对于公式,您可以使用XlsxWriter的utility functions

from xlsxwriter.utility import xl_range 

my_range = xl_range(3, 6, 20, 6)  # G4:G21
© www.soinside.com 2019 - 2024. All rights reserved.