-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxlsx_demo.py
38 lines (32 loc) · 1012 Bytes
/
xlsx_demo.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import xlsxwriter
def create_workbook(filename):
"""Create a new workbook on which we can work."""
workbook = xlsxwriter.Workbook(filename)
return workbook
def create_worksheet(workbook):
"""Add a new worksheet in the workbook."""
worksheet = workbook.add_worksheet()
return worksheet
def write_data(worksheet, data):
"""Write data to the worksheet."""
for row in range(len(data)):
for col in range(len(data[row])):
worksheet.write(row, col, data[row][col])
worksheet.write(len(data), 0, "Avg. Age")
# len(data) will give the next index to write to
avg_formula = f"=AVERAGE(B{1}:B{len(data)})"
worksheet.write(len(data), 1, avg_formula)
def close_workbook(workbook):
"""Close an opened workbook."""
workbook.close()
if __name__ == '__main__':
data = [
['John Doe', 38],
['Adam Cuvver', 22],
['Stacy Martin', 28],
['Tom Harris', 42]
]
workbook = create_workbook('sample_workbook.xlsx')
worksheet = create_worksheet(workbook)
write_data(worksheet, data)
close_workbook(workbook)