Creating and naming column in openpyxl
Question:
Background-
The following code snippet will iterate over all worksheets in a workbook, and write a formula to every last column –
import openpyxl
filename = 'filename.xlsx'
filename_output = 'filename_output.xlsx'
wb = openpyxl.load_workbook(filename)
for sheet in wb.worksheets:
sheet.insert_cols(sheet.max_column)
for row in sheet.iter_rows():
row[-1].value = "=SUMIFS(J:J,M:M,@M:M)"
wb.save(filename_output)
Question –
I cannot find documentation on how to name the column. Does anyone know how to achieve this?
Context –
I want this column (in each worksheet) to be called ‘Calculation’.
Answers:
To get the last column, you can use sheet.max_column
. Once you have updated the formulas, you can use sheet.cell(1,col).value = "Calc"
to update the header. Updated code below…
import openpyxl
filename = 'filename.xlsx'
filename_output = 'filename_output.xlsx'
wb = openpyxl.load_workbook(filename)
for sheet in wb.worksheets:
sheet.insert_cols(sheet.max_column)
for row in sheet.iter_rows():
row[-1].value = "=SUMIFS(J:J,M:M,@M:M)"
sheet.cell(1,sheet.max_column).value = "Calculation" ## Add line inside FOR loop
wb.save(filename_output)
Output would look something like this.
Background-
The following code snippet will iterate over all worksheets in a workbook, and write a formula to every last column –
import openpyxl
filename = 'filename.xlsx'
filename_output = 'filename_output.xlsx'
wb = openpyxl.load_workbook(filename)
for sheet in wb.worksheets:
sheet.insert_cols(sheet.max_column)
for row in sheet.iter_rows():
row[-1].value = "=SUMIFS(J:J,M:M,@M:M)"
wb.save(filename_output)
Question –
I cannot find documentation on how to name the column. Does anyone know how to achieve this?
Context –
I want this column (in each worksheet) to be called ‘Calculation’.
To get the last column, you can use sheet.max_column
. Once you have updated the formulas, you can use sheet.cell(1,col).value = "Calc"
to update the header. Updated code below…
import openpyxl
filename = 'filename.xlsx'
filename_output = 'filename_output.xlsx'
wb = openpyxl.load_workbook(filename)
for sheet in wb.worksheets:
sheet.insert_cols(sheet.max_column)
for row in sheet.iter_rows():
row[-1].value = "=SUMIFS(J:J,M:M,@M:M)"
sheet.cell(1,sheet.max_column).value = "Calculation" ## Add line inside FOR loop
wb.save(filename_output)
Output would look something like this.