用Python非常流行的openpyxl库对Excel(.xlsx格式)文件进行创建、读取、写入、显示等操作

用Python非常流行的openpyxl库对Excel文件进行创建、读取、写入、显示等操作

安装openpyxl库

使用国内镜像(阿里云)安装openpyxl库


导入openpyxl库

python 复制代码
from openpyxl import load_workbook
from openpyxl import Workbook
import os

一、创建Excel文件

python 复制代码
# 创建Excel文件
def create_excel(file_name:str, sheet_names:list):

    # 检查文件是否存在
    if os.path.exists(file_name):
        return

    # 创建工作簿
    wb = Workbook()

    if sheet_names:
        # 创建工作表
        for sheet_name in sheet_names:
            if sheet_name not in wb.sheetnames:
                wb.create_sheet(sheet_name)
        
        # 删除默认工作表
        if 'Sheet' in wb.sheetnames:
            del wb['Sheet']

    # 保存文件
    wb.save(file_name)
    print('Excel文件创建成功......')

二、写入数据到Excel文件

python 复制代码
# 写入数据到Excel文件
def write_excel(file_name:str, sheet_name:str):
    # 文件是否存在
    if not os.path.exists(file_name):
        print('Excel文件不存在......')
        return

    # 加载工作簿
    wb = load_workbook(file_name)

    # 工作表是否存在
    if sheet_name not in wb.sheetnames:
        wb.create_sheet(sheet_name)

    # 激活工作表
    ws = wb[sheet_name]

    # 向工作表添加数据 方式1
    # print('写数据方式1......')
    # ws.append(['学号', '姓名', '性别', '年龄', '成绩'])
    # ws.append(['2025121', '凌盛羽', 26, 2, 98])
    # ws.append(['2025122', '林国瑞', 29, 3, 92])
    # ws.append(['2025123', '林玟书', 38, 4, 96])
    # ws.append(['2025124', '林雅南', 32, 1, 93])
    # ws.append(['2025125', '江奕云', 40, 3, 99])

    # 向工作表添加数据 方式2
    print('写数据方式2......')
    ws['A1'] = "姓名"
    ws['B1'] = "年龄"
    ws['C1'] = "爱好"
    ws.cell(row=2, column=1, value="张三")       # A2
    ws.cell(row=2, column=2, value=29)           # B2
    ws.cell(row=2, column=3, value='篮球,羽毛球') # C2

    # 保存文件
    wb.save(file_name)



三、指定位置写入数据到Excel文件

python 复制代码
# 指定位置写入数据到Excel文件
def write_position_excel(file_name:str, sheet_name:str):
    # 文件是否存在
    if not os.path.exists(file_name):
        print('Excel文件不存在......')
        return

    # 加载工作簿
    wb = load_workbook(file_name)

    # 工作表是否存在
    if sheet_name not in wb.sheetnames:
        wb.create_sheet(sheet_name)

    # 激活工作表
    ws = wb[sheet_name]

    # 写入数据
    dat = [
        ['学号', '姓名', '年龄', '成绩'],
        ['2985121', '凌盛羽', 26, 98],
        ['2225123', '林国瑞', 29, 92],
        ['2925126', '林玟书', 38, 96],
        ['2625127', '林雅南', 32, 93],
        ['2325120', '江奕云', 40, 99]
    ]

    print('指定位置写数据......')
    for row_idx, row_data in enumerate(dat, start=3):  # 从第5行开始写入
        for col_idx, value in enumerate(row_data, start=6):  # 从第6列开始写入
            ws.cell(row=row_idx, column=col_idx, value=value)

    # 保存文件
    wb.save(file_name)

四、读取Excel文件数据

python 复制代码
# 读取Excel文件数据
def write_read_excel(file_name:str, sheet_name:str):
    # 文件是否存在
    if not os.path.exists(file_name):
        print('Excel文件不存在......')
        return

    # 加载工作簿
    wb = load_workbook(file_name, read_only=True)

    # 工作表是否存在
    if sheet_name not in wb.sheetnames:
        print('工作表不存在......')
        return
    
    # 激活工作表
    ws = wb[sheet_name]

    # 读取指定单元格数据 方式1
    # print('读数据方式1......')
    # cell_a1 = ws['A1'].value
    # cell_b2 = ws.cell(row=2, column=2).value
    # print(f"A1单元格:{cell_a1}, B2单元格:{cell_b2}")


    # 读取整行数据 方式2
    # print('读数据方式2......')
    # row1  = [cell.value for cell in ws[5]]  # 第2行所有单元格
    # print("行数据:", row1)


    # 读取指定范围数据(A1:K10) 方式3
    # print('读数据方式3......')
    # for row in ws['A1:K10']:
    #     row_values = [cell.value for cell in row]
    #     print(row_values)


    # 遍历所有行(含空行检测) 方式4
    print('读数据方式4......')
    for row in ws.iter_rows(min_row=1, max_row=ws.max_row, values_only=True): #
        if any(cell is not None for cell in row):  # 跳过空行
            print(row)

    # 关闭文件
    wb.close()

五、主函数

python 复制代码
def main():
    create_excel(r'xsuper.xlsx',['demox', 'xdemo', 'test']) # 创建Excel文件
    write_excel(r'xsuper.xlsx', 'xdemo') # 写入数据到Excel文件
    write_position_excel(r'xsuper.xlsx', 'test') # 指定位置写入数据到Excel文件
    write_read_excel(r'xsuper.xlsx', 'test') # 读取Excel文件数据


if __name__ == '__main__':
    main()
相关推荐
DogDaoDao11 分钟前
【第10篇】Python 异常处理与调试入门
python·深度学习·ai·程序员·大模型·异常处理与调试
程序员雷欧24 分钟前
Java 反射深度解析:从原理到源码的全面剖析
java·开发语言·python
上海云盾商务经理杨杨37 分钟前
SQL 盲注入渗透实战!无报错页面也能成功注入
数据库·sql
rannn_11140 分钟前
【力扣hot100】链表专题|21、2、19、24、92、25
java·数据结构·算法·leetcode·链表·开发
我的xiaodoujiao1 小时前
快速学习Python基础知识详细图文教程18--多线程
开发语言·python·学习·测试工具
汉拓3D数字化1 小时前
设计标准化怎么落地?企业设计标准化的5阶段实施路径
科技·excel·系统·软件
鹿角片ljp1 小时前
LeetCode 21. 合并两个有序链表
算法·leetcode·链表
秋田君1 小时前
QT_绘图原理双缓冲机制
服务器·数据库·qt
一条闲鱼_mytube2 小时前
深入理解 Pinecone 向量数据库:从云服务到索引原理,一篇讲透
数据库
❀搜不到2 小时前
isat-sam分割导出掩码图
开发语言·python