Python openpyxl 插入折线图实例


Posted in Python onApril 17, 2020

我就废话不多说了,还是直接看代码吧!

import os
import openpyxl

from datetime import date
from openpyxl import Workbook

from openpyxl.chart import (
 Series,
 LineChart,
 Reference,
)
def add_line_chart(title, wss, min_col, min_row, max_col, max_row):
 c1 = LineChart()
 c1.title = title # 图的标题
 c1.style = 12 # 线条的style
 c1.y_axis.title = 'percent' # y坐标的标题
 if 'IDC' not in title:
  c1.x_axis.number_format = 'd-mmm' # 规定日期格式 这是月,年格式
  c1.x_axis.majorTimeUnit = "Months" # 规定日期间隔 注意days;Months大写
 c1.x_axis.title = "Date" # x坐标的标题
 data = Reference(wss, min_col=min_col, min_row=min_row, max_col=max_col, max_row=max_row) # 图像的数据 起始行、起始列、终止行、终止列
 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") # 将图表添加到 sheet中


def save_data_to_excel(file_name, target_sheet_name):
 select_cursor = connect.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 os.path.exists(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

 sheet.title = 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))

 wb.save(file_name)
 pass

Python openpyxl 插入折线图实例

补充知识:python plotly line chart 折线图

我就废话不多说了,还是直接看代码吧!

# 1 折线图数据
# trace1 - 基本格式
# trace2 - 更多参数
trace1 = go.Scatter(
 x = x1,
 y = y2,
)
trace2 = go.Scatter(
 x = x2,
 y = y2,
 mode = 'lines', # 模式:lines 线,markers 点。可用“+”相连
 name = 'line2', # 折线名,显示于图例
 connectgaps = True # 连接缺失点两端 默认False
 line = dict(
  color = ('rgb(205, 12, 24)'), # 颜色
  width = 4, #线宽
  dash = 'dash') # 虚线: dash 一一,dot ···,dashdot 一·一
) 
)

# 2 打包数据
data = [trace1,trace2]

# 3 格式
layout = dict(title = '折线',
    xaxis = dict(title = '时间'), # 横轴坐标
    yaxis = dict(title = '数量'), # 总轴坐标
    legend=dict(x=1.1,y=1) # 图例位置 
    )

# 4 打包数据+格式
fig = dict(data=data, layout=layout)

# 5 画图
py.iplot(fig, filename='styled-line')

以上这篇Python openpyxl 插入折线图实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python类的动态修改的实例方法
Mar 24 Python
django rest framework之请求与响应(详解)
Nov 06 Python
pandas对指定列进行填充的方法
Apr 11 Python
vue.js实现输入框输入值内容实时响应变化示例
Jul 07 Python
python利用小波分析进行特征提取的实例
Jan 09 Python
python os.fork() 循环输出方法
Aug 08 Python
Python如何实现动态数组
Nov 02 Python
使用Python的datetime库处理时间(RPA流程)
Nov 24 Python
python爬取本站电子书信息并入库的实现代码
Jan 20 Python
哪种Python框架适合你?简单介绍几种主流Python框架
Aug 04 Python
如何Tkinter模块编写Python图形界面
Oct 14 Python
python lambda 表达式形式分析
Apr 03 Python
python 画图 图例自由定义方式
Apr 17 #Python
关于python 的legend图例,参数使用说明
Apr 17 #Python
python 实现仿微信聊天时间格式化显示的代码
Apr 17 #Python
python matplotlib实现将图例放在图外
Apr 17 #Python
python 比较字典value的最大值的几种方法
Apr 17 #Python
Python3 selenium 实现QQ群接龙自动化功能
Apr 17 #Python
python plt可视化——打印特殊符号和制作图例代码
Apr 17 #Python
You might like
推荐php模板技术[转]
2007/01/04 PHP
PHP 将dataurl转成图片image方法总结
2016/10/14 PHP
php学习笔记之mb_strstr的基本使用
2018/02/03 PHP
javascript Select标记中options操作方法集合
2008/10/22 Javascript
jQuery $命名冲突解决方案汇总
2014/11/13 Javascript
基于javascript代码实现通过点击图片显示原图片
2015/11/29 Javascript
JavaScript html5 canvas画布中删除一个块区域的方法
2016/01/26 Javascript
基于JavaScript实现前端文件的断点续传
2016/10/17 Javascript
Bootstrap.css与layDate日期选择样式起冲突的解决办法
2017/04/07 Javascript
详解如何将angular-ui的图片轮播组件封装成一个指令
2017/05/09 Javascript
老生常谈javascript的面向对象思想
2017/08/22 Javascript
Vue实现购物车场景下的应用
2017/11/27 Javascript
vue根据进入的路由进行原路返回的方法
2018/09/26 Javascript
JavaScript根据json生成html表格的示例代码
2018/10/24 Javascript
python读取html中指定元素生成excle文件示例
2014/04/03 Python
Python 抓取动态网页内容方案详解
2014/12/25 Python
JS设计模式之责任链模式实例详解
2018/02/03 Python
python顺序执行多个py文件的方法
2019/06/29 Python
Django app配置多个数据库代码实例
2019/12/17 Python
Python对wav文件的重采样实例
2020/02/25 Python
Python实现AI自动抠图实例解析
2020/03/05 Python
python 链接sqlserver 写接口实例
2020/03/11 Python
用python对excel进行操作(读,写,修改)
2020/12/25 Python
CSS3动画:5种预载动画效果实例
2017/04/05 HTML / CSS
基于HTML5的WebGL经典3D虚拟机房漫游动画
2017/11/15 HTML / CSS
Lacoste澳大利亚官网:服装、鞋类及配饰
2018/11/14 全球购物
美国波西米亚风格精品店:South Moon Under
2019/10/26 全球购物
教师找工作推荐信
2013/11/23 职场文书
高中毕业生登记表自我鉴定范文
2014/03/18 职场文书
《水乡歌》教学反思
2014/04/24 职场文书
学校文明单位申报材料
2014/05/06 职场文书
作风转变心得体会
2014/09/02 职场文书
2014年保险公司工作总结
2014/11/22 职场文书
八月一日观后感
2015/06/10 职场文书
详解Python requests模块
2021/06/21 Python
python实现剪贴板的操作
2021/07/01 Python