【python练习】excel中批量插入图形

'''批量插入图表'''
'''
需求描述:E:\PycharmProjects\OJ\simple\项目3 下的所有文件中的所有工作表创建条形图
1、读取每一个工作薄里面的工作表名称 
2、读取每一个工作表
3、创建条形图
'''
import openpyxl
import os
from openpyxl.chart import BarChart, Reference

dirpath = os.path.join(os.getcwd(), '项目3')
for filepath in os.listdir(dirpath): # 遍历目录下的所有文件
    print(filepath) # LLT-10月.xlsx
    ex_file_name = os.path.join(os.getcwd(), '项目3',filepath)
    print(ex_file_name) # E:\PycharmProjects\OJ\simple\项目3\LLT-10月.xlsx
    wb = openpyxl.load_workbook(ex_file_name, data_only=True)
    sheet_names = wb.get_sheet_names()
    print(sheet_names) # ['1001', '1002']
    for sheet_name in sheet_names:
        ws = wb.get_sheet_by_name(sheet_name)
        bc = BarChart()
        bc.title = filepath.split('.')[0] + '-' + sheet_name
        bc.x_axis.title = '代码仓'
        bc.y_axis.title = '白盒覆盖率'
        data = Reference(ws, min_row=1, min_col=2, max_row=56, max_col=3)
        lable = Reference(ws, min_col=1, min_row=2, max_row=56)
        bc.add_data(data, titles_from_data=True)
        bc.set_categories(lable)
        ws.add_chart(bc, 'E1')
    wb.save(ex_file_name)

  

原文地址:https://www.cnblogs.com/zhaoyujiao/p/15635523.html