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()

读取结果如下:

相关推荐
烟花巷子3 小时前
使用Kivy开发跨平台的移动应用
jvm·数据库·python
SPC的存折3 小时前
Python3编程之python基础
开发语言·python
2401_873204653 小时前
Python面向对象编程(OOP)终极指南
jvm·数据库·python
XW01059994 小时前
6-函数-1 使用函数求特殊a串数列和
数据结构·python·算法
m0_569881474 小时前
使用Python进行网络设备自动配置
jvm·数据库·python
波诺波4 小时前
项目pid-control-simulation-main 中的 main.py 代码讲解
开发语言·python
巧妹儿4 小时前
Python 配置管理封神技:pydantic_settings+@lru_cache,支持优先级,安全又高效,杜绝重复加载!
开发语言·python·ai·配置管理
独隅4 小时前
Python AI 全面使用指南:从数据基石到智能决策
开发语言·人工智能·python
胡耀超4 小时前
Web Crawling 网络爬虫全景:技术体系、反爬对抗与全链路成本分析
前端·爬虫·python·网络爬虫·数据采集·逆向工程·反爬虫