XLSXWriter Apply Formula Across Column With Dynami

2019-07-24 05:01发布

问题:

Here's an example from the XSLX Writer documentation:

worksheet.write_formula('A1', '=10*B1 + C1')

Looks simple enough. But what if I want to apply this formula for 'A1:A30'? Also, what if in cell A3, the formula should dynamically update to:

'=10*B3 + C3'

?

I've been unable to do this from looking at the docs. I see a promising option for write_array_formula, but I don't want an array formula.

I've come up with a solution involving looping through each row and column, but I'm hoping there's a simpler one.

回答1:

I've come up with a solution involving looping through each row and column, but I'm hoping there's a simpler one.

That is the only way to do it. Something like this:

import xlsxwriter

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

for row_num in range(1, 21):
    worksheet.write_formula(row_num - 1, 0,
                            '=10*$B%d + $C%d' % (row_num, row_num))

    # Write some data for the formula.
    worksheet.write(row_num - 1, 1, row_num)
    worksheet.write(row_num - 1, 2, row_num)

workbook.close()