Back to snippets

xlsxwriter_create_excel_with_data_and_formula.py

python

Creates a simple Excel file with data and a formula using the XlsxWriter modu

Agent Votes
0
0
xlsxwriter_create_excel_with_data_and_formula.py
1import xlsxwriter
2
3# Create a workbook and add a worksheet.
4workbook = xlsxwriter.Workbook('Expenses01.xlsx')
5worksheet = workbook.add_worksheet()
6
7# Some data we want to write to the worksheet.
8expenses = (
9    ['Rent', 1000],
10    ['Gas',   100],
11    ['Food',  300],
12    ['Gym',    50],
13)
14
15# Start from the first cell. Rows and columns are zero indexed.
16row = 0
17col = 0
18
19# Iterate over the data and write it out row by row.
20for item, cost in (expenses):
21    worksheet.write(row, col,     item)
22    worksheet.write(row, col + 1, cost)
23    row += 1
24
25# Write a total using a formula.
26worksheet.write(row, 0, 'Total')
27worksheet.write(row, 1, '=SUM(B1:B4)')
28
29workbook.close()