I try to get a chart in Excel using Python. The code below works for now but next month a new line will be added. As you can see I now only select until line 64 (categories and values) so if I want to add the next month to the chart, I have to change 64 into 65. Is there a way to automatically add this line next month?
JavaScript
x
60
60
1
# import xlsxwriter module
2
import xlsxwriter
3
4
# Select file and add worksheet
5
workbook = xlsxwriter.Workbook(Bestands_naam)
6
7
worksheet = workbook.add_worksheet('Data FI')
8
9
# Create bold format object
10
bold = workbook.add_format({'bold': 1})
11
12
# create a data list
13
headings = list(df.columns.values)
14
15
data = [
16
list(df['col1']),
17
list(df['col2']),
18
list(df['col3']),
19
]
20
21
# Write a row of data
22
worksheet.write_row('A1', headings, bold)
23
datetime_format = workbook.add_format({'num_format': 'dd/mm/yyyy'})
24
25
# Write a column of data
26
worksheet.write_column('A2', data[0],datetime_format)
27
worksheet.write_column('B2', data[1])
28
worksheet.write_column('C2', data[2])
29
30
# Add new worksheet for chart
31
worksheet = workbook.add_worksheet('Grafiek')
32
33
# Create a bar chart object
34
chart1 = workbook.add_chart({'type': 'column'})
35
36
# Add a data series to a chart
37
38
# Configure the first series.
39
chart1.add_series({
40
'name': ['Data FI', 0, 1],
41
'categories': ['Data FI', 1, 0, 64 , 0],
42
'values': ['Data FI', 1, 1, 64 , 1],
43
})
44
45
# Configure a second series.
46
chart1.add_series({
47
'name': ['Data FI', 0, 2],
48
'categories': ['Data FI', 1, 0, 64, 0],
49
'values': ['Data FI', 1, 2, 64, 2],
50
})
51
52
# Add a chart title
53
chart1.set_title ({'name': ' '})
54
55
# add chart to the worksheet
56
worksheet.insert_chart('B2', chart1, {'x_scale': 2, 'y_scale': 2})
57
58
# Close the Excel file
59
workbook.close()
60
Advertisement
Answer
You could calculate the last row from the df.shape
or len()
of the data. Like this:
JavaScript
1
15
15
1
max_row = len(data[0])
2
3
chart1.add_series({
4
'name': ['Data FI', 0, 1],
5
'categories': ['Data FI', 1, 0, max_row , 0],
6
'values': ['Data FI', 1, 1, max_row , 1],
7
})
8
9
# Configure a second series.
10
chart1.add_series({
11
'name': ['Data FI', 0, 2],
12
'categories': ['Data FI', 1, 0, max_row, 0],
13
'values': ['Data FI', 1, 2, max_row, 2],
14
})
15