1##############################################################################
2#
3# A simple program to write some data to an Excel file using the XlsxWriter
4# Python module.
5#
6# This program is shown, with explanations, in Tutorial 3 of the XlsxWriter
7# documentation.
8#
9# Copyright 2013-2021, John McNamara, jmcnamara@cpan.org
10#
11from datetime import datetime
12import xlsxwriter
13
14# Create a workbook and add a worksheet.
15workbook = xlsxwriter.Workbook('Expenses03.xlsx')
16worksheet = workbook.add_worksheet()
17
18# Add a bold format to use to highlight cells.
19bold = workbook.add_format({'bold': 1})
20
21# Add a number format for cells with money.
22money_format = workbook.add_format({'num_format': '$#,##0'})
23
24# Add an Excel date format.
25date_format = workbook.add_format({'num_format': 'mmmm d yyyy'})
26
27# Adjust the column width.
28worksheet.set_column(1, 1, 15)
29
30# Write some data headers.
31worksheet.write('A1', 'Item', bold)
32worksheet.write('B1', 'Date', bold)
33worksheet.write('C1', 'Cost', bold)
34
35# Some data we want to write to the worksheet.
36expenses = (
37    ['Rent', '2013-01-13', 1000],
38    ['Gas', '2013-01-14', 100],
39    ['Food', '2013-01-16', 300],
40    ['Gym', '2013-01-20', 50],
41)
42
43# Start from the first cell below the headers.
44row = 1
45col = 0
46
47for item, date_str, cost in (expenses):
48    # Convert the date string into a datetime object.
49    date = datetime.strptime(date_str, "%Y-%m-%d")
50
51    worksheet.write_string(row, col, item)
52    worksheet.write_datetime(row, col + 1, date, date_format)
53    worksheet.write_number(row, col + 2, cost, money_format)
54    row += 1
55
56# Write a total using a formula.
57worksheet.write(row, 0, 'Total', bold)
58worksheet.write(row, 2, '=SUM(C2:C5)', money_format)
59
60workbook.close()
61