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 the workbook again.
Ideally, I'd like to also first be able delete all rows from the table (though retaining the table structure).
My initial workbook contains a sheet named "inputData". In this I have a table named "Data" with columns A
, B
, C
, and 2 rows of data.
I also have a csv file named "input.csv" containing the same columns but 4 rows of data.
When I run my code, the data is written into the worksheet, but the table structure is not expanded to encompass the two new rows of data.
Any ideas of how to change the data source of a named table structure using openpyxl?
import csv
from openpyxl import load_workbook
from openpyxl.worksheet.table import Table, TableStyleInfo
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):
if not i == 0:
for j, cell in enumerate(row):
ws.cell(row=i+1, column=j+1).value = cell
wb.save('output.xlsx')
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…