SoFunction
Updated on 2024-11-16

Python openpyxl Inserting a Line Chart Example

I'll cut to the chase, or just look at the code!

import os
import openpyxl

from datetime import date
from openpyxl import Workbook

from  import (
 Series,
 LineChart,
 Reference,
)
def add_line_chart(title, wss, min_col, min_row, max_col, max_row):
 c1 = LineChart()
  = title # Title of figure
  = 12 # Line style
 c1.y_axis.title = 'percent' # Title in y-coordinate
 if 'IDC' not in title:
  c1.x_axis.number_format = 'd-mmm' # This is the month, year format.
  c1.x_axis.majorTimeUnit = "Months" # Specify date intervals Note capitalization of days; Months
 c1.x_axis.title = "Date" # Title in x-coordinate
 data = Reference(wss, min_col=min_col, min_row=min_row, max_col=max_col, max_row=max_row) # of images Starting row, starting column, ending row, ending column
 c1.add_data(data, titles_from_data=True, from_rows=True)
 dates = Reference(wss, min_col=2, min_row=1, max_col=max_col)
 c1.set_categories(dates)
 wss.add_chart(c1, "A6") # Add charts to sheets


def save_data_to_excel(file_name, target_sheet_name):
 select_cursor = ()
 select_sql = "select phone_company, record_date, record_percent from phone_statistics where record_company = '%s'" % target_sheet_name
 if target_sheet_name == "IDC":
  select_sql = "select phone_company, record_q, record_percent from phone_statistics where record_company = '%s'" % target_sheet_name
 select_cursor.execute(select_sql, ())

 data_dic = {}
 all_date = {}
 all_phone_company = {}
 for item in select_cursor:
  if target_sheet_name == "IDC":
   data_dic[item[0] + '_' + item[1]] = item[2]
  else:
   if type(item[1]) == str:
    data_dic[item[0] + '_' + item[1]] = item[2]
   else:
    data_dic[item[0] + '_' + item[1].strftime("%Y-%m-%d")] = item[2]
  all_date[item[1]] = 1
  all_phone_company[item[0]] = 1

 if (file_name):
  wb = openpyxl.load_workbook(file_name)
 else:
  wb = Workbook()

 try:
  wb.remove_sheet(wb['Sheet'])
 except Exception as e:
  pass
 try:
  wb.remove_sheet(wb[target_sheet_name])
 except Exception as e:
  pass

 try:
  sheet = wb[target_sheet_name]
 except Exception as e:
  sheet = wb.create_sheet()

 start_date_index = 'B'
 for each_date in all_date.keys():

  if target_sheet_name == "IDC":
   sheet['%s1' % start_date_index] = each_date
  else:
   if type(each_date) == str:
    sheet['%s1' % start_date_index] = each_date
   else:
    sheet['%s1' % start_date_index] = each_date.strftime("%Y-%m-%d")
  start_date_index = chr(ord(start_date_index) + 1)

 start_name_index = 2
 for each_name in all_phone_company.keys():
  sheet['A%d' % start_name_index] = each_name
  start_name_index += 1

 start_date_index = 'B'
 start_name_index = 2
 for each_date in all_date.keys():
  for each_name in all_phone_company.keys():

   if target_sheet_name == "IDC":
    key = each_name + '_' + each_date
    if key in data_dic:
     sheet['%s%d' % (start_date_index, start_name_index)] = data_dic[key]
   else:
    if type(each_date) == str:
     key = each_name + '_' + each_date
    else:
     key = each_name + '_' + each_date.strftime("%Y-%m-%d")
    if key in data_dic:
     sheet['%s%d' % (start_date_index, start_name_index)] = data_dic[key]
   start_name_index += 1
  start_date_index = chr(ord(start_date_index) + 1)
  start_name_index = 2

  = target_sheet_name
 sheet.column_dimensions['A'].width = 20
 start_date_index = 'B'
 for each_date in all_date.keys():
  sheet.column_dimensions[start_date_index].width = 13
  start_date_index = chr(ord(start_date_index) + 1)

 add_line_chart(target_sheet_name.upper() + "'s Phone Statistics", sheet, 1, 2, len(all_date.keys()) + 1,
     min(15, len(all_phone_company.keys()) + 1))

 (file_name)
 pass

Additional knowledge:python plotly line chart line graph

I'll cut to the chase, or just look at the code!

# 1 Line graph data
# trace1 - basic format
# trace2 - more parameters
trace1 = (
 x = x1,
 y = y2,
)
trace2 = (
 x = x2,
 y = y2,
 mode = 'lines', # Patterns: lines, markers, dots. Can be linked with "+"
 name = 'line2', # Folded line names, shown in the legend
 connectgaps = True # Connect the ends of the missing points Default False
 line = dict(
  color = ('rgb(205, 12, 24)'), # Color
  width = 4, #Line width
  dash = 'dash') # Dashed lines: dash one-one, dot ---, dashdot one-one #
) 
)

# 2 Packaging data
data = [trace1,trace2]

# 3 Format
layout = dict(title = 'Folding lines',
    xaxis = dict(title = 'Time'), # Horizontal axis coordinates
    yaxis = dict(title = 'Number'), # General axis coordinates
    legend=dict(x=1.1,y=1) # Legend location
    )

# 4 Packaging Data + Format
fig = dict(data=data, layout=layout)

# 5 Drawing
(fig, filename='styled-line')

This Python openpyxl Insert Line Chart Example above is all I have to share with you, I hope it can give you a reference, and I hope you can support me more.