XlsxWriter 在编写公式时添加随机字符(@)

XlsxWriter adding random character (@) when writing formula

我正在尝试使用 Python 中的 XlsxWriter 将公式写入 xlsx 文档。

我要写入单元格的内容是:

=SUM(IF($F:$F0=$F,I:I0))

但是当我尝试使用 XlsxWriter 插入公式时,它会这样写:

=SUM(IF(@$F:$F0=$F,I:I0)) 

如您所见,XlsxWriter 中有一个随机的 @,这会导致 #VALUE 错误。手动删除 @ 后,公式将按预期工作。

我将公式字符串打印到终端,打印如下:

=SUM(IF($F:$F0=$F,I:I0))

我该如何解决这个问题?

下面包含相关代码片段...变量被审查为通用

--- 片段 1 ---

for j in range(0,len(LIST_A)):

    if VAR_A == LIST_VAR_A[1]:
        formula = formula_function(row, col, row_start, LIST_B, LIST_C, j)

        print(formula) # this is where I printed the formula to check for an @

        worksheet.write_formula(row, col, formula, LIST_FORMAT[0])

    else: worksheet.write(row, col, CLASS.LIST_MEMBER[j], LIST_FORMAT[0]) 

    col += 1

--- 片段 2 ---

def formula_function(row, col, row_start, LIST_B, LIST_C, j):
    
    # rctc ... from xlsxwriter.utility import xl_rowcol_to_cell as rctc

    CELL_A = rctc(row, col-3-spread_depth, row_abs=True, col_abs=True)
     
    CELL_B1 = rctc(row_start+1+len(LIST_B), col-3-j, row_abs=True, col_abs=True)
    CELL_B2 = rctc(row_start-1+len(LIST_C), col-3-j, row_abs=True, col_abs=True)

    CELL_C1 = rctc(row_start+1+len(LIST_B), col, row_abs=True)
    CELL_C2 = rctc(row_start-1+len(LIST_C), col, row_abs=True)
    
    formula = '=SUM(IF(' + CELL_B1  + ':' + CELL_B2 + '=' + CELL_A + ',' + \
              CELL_C1 + ':' + CELL_C2  + '))'

    return formula

XlsxWriter 没有将 @ 插入到公式中,Excel 365 像这样显示它以指示公式中的位置,当范围或数组时隐式返回单个值可以退货。

来自 Dynamic Arrays - The Implicit Intersection Operator "@" 上的 XlsxWriter 文档:

...

If you are encountering the Implicit Intersection Operator “@” for the first time then it is probably from a point of view of “why is Excel/XlsxWriter putting @s in my formulas”. In practical terms if you encounter this operator, and you don’t intend it to be there, then you should probably write the formula as a CSE (Ctrl+Shift+Enter) or dynamic array function using write_array_formula() or write_dynamic_array_formula().

如果你的情况应该使用动态数组公式:

import xlsxwriter

workbook = xlsxwriter.Workbook('test.xlsx')
worksheet = workbook.add_worksheet()

worksheet.write_dynamic_array_formula(0, 0, 0, 0, '=SUM(IF($F:$F0=$F,I:I0))')

workbook.close()

输出: