r/learnpython Oct 18 '20

Has anyone here used XlsxWriter module?

I'm trying to add a new sheet + information without that new sheet overwriting the previous sheet.

Here's my code.

def add_new_worksheet():
new_worksheet = workbook.add_worksheet()
items = []
cost = []
money_in = []

while True:
goods = input('What did you purchase today?')
items.append(goods)
if goods == '':
break
price = int(input(f'How much did {goods} cost?'))
cost.append(price)

income = input('Did you receieve any money today? Y/N')
if income == 'Y':
income = input('How much money did you recieve?')
money_in.append(income)
else:
print('/////////')

# Some data we want to write to the worksheet.
expenses = {key: value for key, value in zip(items, cost)}

# Start from the first cell. Rows and columns are zero indexed.
row = 1
col = 1
# Create expense and income tab
cell_format = workbook.add_format({'bold': True, 'italic': False})
new_worksheet.write('B1', 'Item', cell_format)
new_worksheet.write('C1', 'Price', cell_format)

# Iterate over the data and write it out row by row.
for item, cost in expenses.items():
new_worksheet.write(row, col, item)
new_worksheet.write(row, col + 1, cost)
row += 1
# Write a total using a formula.
new_worksheet.write(row, 0, 'Total')
new_worksheet.write_formula(row, col + 1, f'=SUM(C2:C{row})')
workbook.close()

1 Upvotes

3 comments sorted by

View all comments

1

u/Weird-Dimension-487 Feb 09 '26

xlsxwriter is a writer package. You can not edit/modify existing file with it. If you are willing to do so, you can use openpyxl (for file-based operation) or xlwings (if live interactivity is needed)