#python #excel #openpyxl
Вопрос:
Следующий код вычисляет сумму трех столбцов, используя цикл for и openpyxl. Он возвращает в A5 сумму A2:A4. Формула в Excel записывается между фигурными скобками. В моем случае мне нужно нажать enter, чтобы получить значение. Это немного раздражает. Я хочу, чтобы openxl вставил «чистую» формулу. Может быть, это больше вопрос Excel, чем вопрос на Python?
data = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]),
columns=['a', 'b', 'c'])
data
wb1 = openpyxl.Workbook()
ws1 = wb1.active
rows = dataframe_to_rows(data, index=False, header=False)
for r_idx, row in enumerate(rows, 2):
for c_idx, value in enumerate(row, 1):
ws1.cell(row=r_idx, column=c_idx, value=value)
ws1["A5"] = "=SUMMA(A2:A4)"
ws1.formula_attributes['A5'] = {'t': 'array', 'ref': "A5"}
colNum = 0
for col in ws1.iter_cols(min_row=5, max_row=5, min_col=1, max_col=3):
colNum = 1
for cell in col:
ws1["{0}5".format(get_column_letter(colNum))] = '=SUMMA({0}2 {0}4)'.format(get_column_letter(colNum))
ws1.formula_attributes['{0}5'.format(get_column_letter(colNum))] = {'t': 'array', 'ref': "{0}5".format(get_column_letter(colNum))}
#cell.value = '=SUMMA({0}2:{0}4)'.format(get_column_letter(colNum))
wb1.save('test.xlsx')