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中的startswith和endswith函数使用实例
Aug 25 Python
python使用三角迭代计算圆周率PI的方法
Mar 20 Python
在Python中操作列表之List.append()方法的使用
May 20 Python
Linux-ubuntu16.04 Python3.5配置OpenCV3.2的方法
Apr 02 Python
Python调用服务接口的实例
Jan 03 Python
python 求一个列表中所有元素的乘积实例
Jun 11 Python
matlab中二维插值函数interp2的使用详解
Apr 22 Python
python实现时间序列自相关图(acf)、偏自相关图(pacf)教程
Jun 03 Python
详解Flask前后端分离项目案例
Jul 24 Python
Python实现弹球小游戏
Aug 01 Python
python基于opencv批量生成验证码的示例
Apr 28 Python
8g内存用python读取10文件_面试题-python 如何读取一个大于 10G 的txt文件?
May 28 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
LAMP环境使用Composer安装Laravel的方法
2017/03/25 PHP
JavaScript 关键字屏蔽实现函数
2009/08/02 Javascript
24款非常有用的 jQuery 插件分享
2011/04/06 Javascript
js修改input的type属性问题探讨
2013/10/12 Javascript
Checbox的操作含已选、未选及判断代码
2013/11/07 Javascript
Jquery getJSON方法详细分析
2013/12/26 Javascript
JavaScript正则表达式之multiline属性的应用
2015/06/16 Javascript
详解JavaScript正则表达式之分组匹配及反向引用
2016/03/09 Javascript
jquery的checkbox,radio,select等方法小结
2016/08/30 Javascript
原生js实现无缝轮播图效果
2017/01/11 Javascript
js实现扫雷小程序的示例代码
2017/09/27 Javascript
webpack打包并将文件加载到指定的位置方法
2018/02/22 Javascript
详解js创建对象的几种方法及继承
2019/04/12 Javascript
[00:53]TI3正赛第三天 DK怒破A队不败金身 现场国旗飘扬热血激昂
2013/08/10 DOTA
[01:15:45]DOTA2上海特级锦标赛B组小组赛#1 Alliance VS Spirit第一局
2016/02/26 DOTA
python中bisect模块用法实例
2014/09/25 Python
Python匿名函数及应用示例
2019/04/09 Python
使用python实现ftp的文件读写方法
2019/07/02 Python
解决os.path.isdir() 判断文件夹却返回false的问题
2019/11/29 Python
python可迭代对象去重实例
2020/05/15 Python
简单介绍一下pyinstaller打包以及安全性的实现
2020/06/02 Python
CSS3 :nth-child()伪类选择器实现奇偶行显示不同样式
2013/11/05 HTML / CSS
CSS Grid布局教程之网格单元格布局
2014/12/30 HTML / CSS
加拿大票务网站:Ticketmaster加拿大
2017/07/17 全球购物
美国瑜伽品牌:Gaiam
2017/10/31 全球购物
大学生通用个人的自我评价
2014/02/10 职场文书
学习“七一”讲话精神体会
2014/07/08 职场文书
2014年民政局关于保密工作整改措施
2014/09/19 职场文书
党的群众路线教育实践活动个人批评与自我批评
2014/10/16 职场文书
金融专业银行实习证明模板
2014/11/28 职场文书
2015年城市管理工作总结
2015/05/23 职场文书
给学校的建议书400字
2015/09/14 职场文书
大学自主招生自荐信(2016精选篇)
2016/01/28 职场文书
优秀共产党员事迹材料2016
2016/02/29 职场文书
我的暑假生活作文(五年级)范文
2019/08/07 职场文书
MySQL中连接查询和子查询的问题
2021/09/04 MySQL