使用Python+openpyxl实现导出自定义样式的Excel文件

简介: 本文介绍了如何使用Python的openpyxl库导出具有自定义样式的Excel文件,包括设置字体、对齐方式、行列宽高、边框和填充等样式,并提供了完整的示例代码和运行效果截图。

前言

之前项目中的导出Excel文件操作都是在前端完成的,项目是由vue+vite构建的,效果还不错的,所需依赖包如下所示。

npm i xlsx@0.18.5
npm i xlsx-style-vite@0.0.2

现在了解了一下Python的openpyxl依赖库后,试一下编写脚本进行Excel导出,效果也不错的。

一、导入依赖

pip install openpyxl

二、示例代码

(1)export_excel_demo.py

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

from openpyxl.styles import Alignment, PatternFill, Border, Side, Font
from openpyxl.workbook import Workbook

if __name__ == '__main__':
    # 定义表头键值对列表
    keyMap = {
   
   
        'hero': '英雄',
        'level': '等级',
        'gold': '金币',
        'kill': '击杀',
        'be_killed': '被击杀',
        'assists': '助攻',
        'score': '评分',
        'is_mvp': '是否MVP',
    }

    # 定义目标数组列表
    targetList = [
        {
   
   
            'hero': '云缨',
            'level': 15,
            'gold': 20013,
            'kill': 21,
            'be_killed': 5,
            'assists': 16,
            'score': 12.9,
            'is_mvp': True,
        },
        {
   
   
            'hero': '王昭君',
            'level': 15,
            'gold': 17336,
            'kill': 2,
            'be_killed': 6,
            'assists': 20,
            'score': 7.5,
            'is_mvp': False,
        },
        {
   
   
            'hero': '狄仁杰',
            'level': 15,
            'gold': 16477,
            'kill': 9,
            'be_killed': 8,
            'assists': 22,
            'score': 8.4,
            'is_mvp': False,
        },
        {
   
   
            'hero': '兰陵王',
            'level': 15,
            'gold': 16154,
            'kill': 15,
            'be_killed': 8,
            'assists': 14,
            'score': 8.6,
            'is_mvp': False,
        },
        {
   
   
            'hero': '赵怀真',
            'level': 15,
            'gold': 17414,
            'kill': 6,
            'be_killed': 6,
            'assists': 21,
            'score': 10.2,
            'is_mvp': False,
        },
    ]

    # 将目标对象列表转为二维数组列表
    processList = []
    for e in targetList:
        arr = []
        for i in keyMap:
            arr.append(e.get(i))
        processList.append(arr)

    # 将表头数组列表追加到二维数组列表中
    lableArr = []
    for i in keyMap:
        lableArr.append(keyMap.get(i) + '-' + i)
    processList.insert(0, lableArr)

    # 打印加工后的二维数组列表
    # print(processList)

    # 创建一个工作簿
    wb = Workbook()

    # 获取当前活动的工作表
    ws = wb.active

    # 设置工作表的名称
    ws.title = u'胜利匹配赛'

    # 往工作表写入数据
    r = 1
    for line in processList:
        for col in range(1, len(line) + 1):
            ws.cell(row=r, column=col).value = line[col - 1]
        r += 1

    # 设置行高和列宽
    ws.column_dimensions["A"].width = 15
    ws.column_dimensions["B"].width = 10
    ws.column_dimensions["C"].width = 20
    ws.column_dimensions["D"].width = 20
    ws.column_dimensions["E"].width = 20
    ws.column_dimensions["F"].width = 20
    ws.column_dimensions["G"].width = 20
    ws.column_dimensions["H"].width = 20
    ws.row_dimensions[1].height = 20

    for row in ws:
        # print(row)
        for cell in row:
            # print(cell)  # 单元格对象
            # print(cell.value)  # 单元格的值
            # print(cell.row)  # 单元格所在的列
            # print(cell.column)  # 单元格所在的行
            # print(cell.coordinate)  # 单元格的坐标,如:A1
            string = str(cell.coordinate)  # 单元格的坐标,如:A1

            # 在字符串中提取所有数字
            num = ''.join([char for char in string if char.isdigit()])
            # print(num)

            # 匹配非首行的所有单元格
            if not ('1' == str(num)):
                # 设置字体
                cell.font = Font(
                    name="Calibri",  # 字体
                    size=11,  # 字体大小
                    color="000000",  # 字体颜色,用16进制rgb表示
                    bold=False,  # 是否加粗,True/False
                    italic=False,  # 是否斜体,True/False
                    strike=False,  # 是否使用删除线,True/False
                    # underline='singleAccounting',  # 下划线, 可选'singleAccounting', 'double', 'single', 'doubleAccounting'
                )

                # 设置布局
                cell.alignment = Alignment(
                    horizontal='center',  # 水平对齐,可选general、left、center、right、fill、justify、centerContinuous、distributed
                    vertical='center',  # 垂直对齐, 可选top、center、bottom、justify、distributed
                    text_rotation=0,  # 字体旋转,0~180整数
                    wrap_text=False,  # 是否自动换行
                    shrink_to_fit=False,  # 是否缩小字体填充
                    indent=0,  # 缩进值
                )

                # 设置填充
                cell.fill = PatternFill(
                    patternType="solid",  # 填充类型,可选none、solid、darkGray、mediumGray、lightGray、lightDown、lightGray、lightGrid
                    fgColor="ffffcc",  # 前景色,16进制rgb
                    bgColor="ff2600",  # 背景色,16进制rgb
                    # fill_type=None,  # 填充类型
                    # start_color=None, # 前景色,16进制rgb
                    # end_color=None    # 背景色,16进制rgb
                )

                # 设置边框
                side = Side(
                    style="thin",  # 边框样式,可选dashDot、dashDotDot、dashed、dotted、double、hair、medium、mediumDashDot、mediumDashDotDot、mediumDashed、slantDashDot、thick、thin
                    color="000000",  # 边框颜色,16进制rgb表示
                )
                cell.border = Border(
                    top=side,  # 上
                    bottom=side,  # 下
                    left=side,  # 左
                    right=side,  # 右
                    diagonal=side  # 对角线
                )
            # 匹配首行的单元格
            else:
                # 设置字体
                cell.font = Font(
                    name="宋体",  # 字体
                    size=11,  # 字体大小
                    color="ffffff",  # 字体颜色,用16进制rgb表示
                    bold=False,  # 是否加粗,True/False
                    italic=False,  # 是否斜体,True/False
                    strike=False,  # 是否使用删除线,True/False
                    # underline='singleAccounting',  # 下划线, 可选'singleAccounting', 'double', 'single', 'doubleAccounting'
                )

                # 设置布局
                cell.alignment = Alignment(
                    horizontal='left',  # 水平对齐,可选general、left、center、right、fill、justify、centerContinuous、distributed
                    vertical='center',  # 垂直对齐, 可选top、center、bottom、justify、distributed
                    text_rotation=0,  # 字体旋转,0~180整数
                    wrap_text=False,  # 是否自动换行
                    shrink_to_fit=False,  # 是否缩小字体填充
                    indent=0,  # 缩进值
                )

                # 设置填充
                cell.fill = PatternFill(
                    patternType="solid",  # 填充类型,可选none、solid、darkGray、mediumGray、lightGray、lightDown、lightGray、lightGrid
                    fgColor="5e7ce0",  # 前景色,16进制rgb
                    bgColor="9bc2e6",  # 背景色,16进制rgb
                    # fill_type=None,  # 填充类型
                    # start_color=None, # 前景色,16进制rgb
                    # end_color=None    # 背景色,16进制rgb
                )

                # 设置边框
                side = Side(
                    style="thin",  # 边框样式,可选dashDot、dashDotDot、dashed、dotted、double、hair、medium、mediumDashDot、mediumDashDotDot、mediumDashed、slantDashDot、thick、thin
                    color="000000",  # 边框颜色,16进制rgb表示
                )
                cell.border = Border(
                    top=side,  # 上
                    bottom=side,  # 下
                    left=side,  # 左
                    right=side,  # 右
                    diagonal=side  # 对角线
                )

    # 将工作簿保存到磁盘
    wb.save('王者荣耀战绩.xlsx')

三、运行效果

四、参考资料

【openpyxl】设置样式(字体样式、行列宽高、对齐方式、边框、填充和渐变)_openpyxl alignment_冰冷的希望的博客-CSDN博客

目录
相关文章
|
5月前
|
监控 机器人 编译器
如何将python代码打包成exe文件---PyInstaller打包之神
PyInstaller可将Python程序打包为独立可执行文件,无需用户安装Python环境。它自动分析代码依赖,整合解释器、库及资源,支持一键生成exe,方便分发。使用pip安装后,通过简单命令即可完成打包,适合各类项目部署。
1040 68
|
6月前
|
缓存 监控 供应链
唯品会自定义 API 自定义操作深度分析及 Python 实现
唯品会开放平台提供丰富API,支持商品查询、订单管理、促销活动等电商全流程操作。基于OAuth 2.0认证机制,具备安全稳定的特点。通过组合调用基础接口,可实现数据聚合、流程自动化、监控预警及跨平台集成,广泛应用于供应链管理、数据分析和智能采购等领域。结合Python实现方案,可高效完成商品搜索、订单分析、库存监控等功能,提升电商运营效率。
|
6月前
|
缓存 监控 供应链
京东自定义 API 操作深度分析及 Python 实现
京东开放平台提供丰富API接口,支持商品、订单、库存等电商全链路场景。通过自定义API组合调用,可实现店铺管理、数据分析、竞品监控等功能,提升运营效率。本文详解其架构、Python实现与应用策略。
缓存 监控 供应链
161 0
缓存 监控 数据挖掘
136 0
|
6月前
|
数据可视化 Linux iOS开发
Python脚本转EXE文件实战指南:从原理到操作全解析
本教程详解如何将Python脚本打包为EXE文件,涵盖PyInstaller、auto-py-to-exe和cx_Freeze三种工具,包含实战案例与常见问题解决方案,助你轻松发布独立运行的Python程序。
1604 2
|
7月前
|
缓存 数据可视化 Linux
Python文件/目录比较实战:排除特定类型的实用技巧
本文通过四个实战案例,详解如何使用Python比较目录差异并灵活排除特定文件,涵盖基础比较、大文件处理、跨平台适配与可视化报告生成,助力开发者高效完成目录同步与数据校验任务。
251 0
|
8月前
|
安全 Linux 网络安全
Python极速搭建局域网文件共享服务器:一行命令实现HTTPS安全传输
本文介绍如何利用Python的http.server模块,通过一行命令快速搭建支持HTTPS的安全文件下载服务器,无需第三方工具,3分钟部署,保障局域网文件共享的隐私与安全。
2033 0
|
8月前
|
数据管理 开发工具 索引
在Python中借助Everything工具实现高效文件搜索的方法
使用上述方法,你就能在Python中利用Everything的强大搜索能力实现快速的文件搜索,这对于需要在大量文件中进行快速查找的场景尤其有用。此外,利用Python脚本可以灵活地将这一功能集成到更复杂的应用程序中,增强了自动化处理和数据管理的能力。
668 0
|
8月前
|
编译器 Python
如何利用Python批量重命名PDF文件
本文介绍了如何使用Python提取PDF内容并用于文件重命名。通过安装Python环境、PyCharm编译器及Jupyter Notebook,结合tabula库实现PDF数据读取与处理,并提供代码示例与参考文献。

推荐镜像

更多