I\'m currently honing my python / excel skills, and have run into an issue with openpyxl
I am trying to open a workbook, replace rows in an existing table, and save
I figured out the answer to my question.
I am able to access the table from openpyxl, change the ref (range) and then save it back again.
This enables me to enter more data into the same table, and have my formulas on my other worksheet take the new data into account.
This will be a very helpful feature, when I need to push a lot of data into an existing excel sheet without breaking references in the future.
import csv
from openpyxl import load_workbook
from openpyxl.worksheet.table import Table, TableStyleInfo
tableName = 'Data'
style = TableStyleInfo(name="TableStyleMedium9", showFirstColumn=False,
showLastColumn=False, showRowStripes=True, showColumnStripes=False)
def colnum_string(n):
string = ""
while n > 0:
n, remainder = divmod(n - 1, 26)
string = chr(65 + remainder) + string
return string
wb = load_workbook(filename = 'workbook.xlsx')
ws = wb["inputData"]
with open('input.csv', newline='', encoding='utf-8-sig') as f:
reader = csv.reader(f, delimiter=';')
for i, row in enumerate(reader):
for j, cell in enumerate(row):
if not i == 0:
ws.cell(row=i+1, column=j+1).value = float(cell)
else:
ws.cell(row=i+1, column=j+1).value = cell
maxRef = [i,j]
for i, table in enumerate(ws._tables):
if table.name == tableName:
tableRef = i
resTable = Table(displayName="Data", ref="A1:{}{}".format(colnum_string(maxRef[0]), maxRef[1]))
resTable.tableStyleInfo = style
ws._tables[tableRef] = resTable
wb.save('output.xlsx')