python用openpyxl操作excel-读取sheet中数据

python用openpyxl操作excel-读取sheet中数据

python 复制代码
import logging
import com.pro001.log.pro_log_config as pro_log_config
from openpyxl import Workbook, load_workbook
from openpyxl.styles import  Font, Alignment, Side, PatternFill, Border
import os
import datetime
import random
import pandas as pd


def excel_read_sheet_data(file_path, sheet_name):
    """ 读取Excel文件指定sheet内容 """
    if not os.path.exists(file_path):
        logger.error(f'文件{file_path}不存在!')
        return None
    wb = load_workbook(file_path)
    if not wb:
        logger.error(f'文件{file_path}不存在!')
        return None
    if sheet_name not in wb.sheetnames:
        logger.error(f'文件{file_path}中不存在{sheet_name}工作表!')
        return None
    
    # 获取指定sheet的行数和列数
    print('-' * 40, 'read_data_rows', '-' * 40)
    all_rows = []
    ws = load_workbook(file_path, data_only=True)[sheet_name]
    for row in ws.iter_rows():
        data_rows = [cell.value for cell in row]
        all_rows.append(data_rows)
        print('rows data:', data_rows)
    print('all rows data:\n', all_rows)
    return all_rows


def main():
    """主函数"""
    excel_read_sheet_data(r'F:\appData\20251207_211304.xlsx', 'TB01')    


if __name__ == '__main__':
    print('-' * 60)
    main()

读取结果如下:

相关推荐
阿尔的代码屋8 小时前
[大模型实战 07] 基于 LlamaIndex ReAct 框架手搓全自动博客监控 Agent
人工智能·python
AI探索者1 天前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者1 天前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh1 天前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅1 天前
Python函数入门详解(定义+调用+参数)
python
曲幽1 天前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
两万五千个小时1 天前
落地实现 Anthropic Multi-Agent Research System
人工智能·python·架构
哈里谢顿1 天前
Python 高并发服务限流终极方案:从原理到生产落地(2026 实战指南)
python
用户8356290780512 天前
无需 Office:Python 批量转换 PPT 为图片
后端·python
markfeng82 天前
Python+Django+H5+MySQL项目搭建
python·django