python利用xlrd库处理Excel

工作中经常需要处理Excel,所以自己稍微写了一个函数,方便以后自己使用.大家也可以借鉴下.

  • excel_file_name : 这里写Excel的路径,和python同一个目录下的话直接写文件名字即可
  • sheet_name : 写要处理的sheet的名字,默认Sheet1
  • start_row : 开始的行
  • end_row : 结束的行(默认所有行)
  • start_col : 开始的列
  • end_col : 结束的列(默认所有列)

返回一个列表,里面是根据首行Name形成的字典.应该能处理大多数excel.

复制代码
# -*- coding: utf-8 -*-
import xlrd


def read_excel(excel_file_name='hello.xlsx', sheet_name='Sheet1', start_row=0, end_row=0, start_col=0, end_col=0 ):
    try:
        data = xlrd.open_workbook(excel_file_name)
    except Exception as e:
        print(str(e))
    table = data.sheet_by_name(sheet_name)
    if end_row == 0:
        end_row = table.nrows
    column_names = table.row_values(start_row)
    if end_col == 0:
        end_col = len(column_names)
    excel_list = []
    for rownum in range(start_row+1, end_row):
        row = table.row_values(rownum)
        if row:
            app = {}
            for i in range(start_col, end_col):
                app[column_names[i]] = row[i]
            excel_list.append(app)
    return excel_list
相关推荐
杨女士YRJ20 分钟前
python+pytest+01
python·pytest
鸽芷咕27 分钟前
Mu Editor 鸿蒙 PC 适配全记录:用 Qt 与嵌入式 CPython 重建教学型 Python IDE
python·qt·harmonyos
微软技术分享44 分钟前
基于 HuggingFace Tokenizers 训练自定义分词器
python·ubuntu·大模型·huggingface
gf13211111 小时前
python_调用远程服务器上的openclaw
服务器·python·php
lbb 小魔仙1 小时前
Jupyter Notebook / Lab 深度配置指南:插件 + 内核 + 远程访问 + 容器化部署
ide·python·jupyter
2601_962300471 小时前
python是跨平台的吗
python·开源·跨平台·面向对象·
2401_844582951 小时前
软件架构设计与持续重构:模块化开发实战建
python
东莞市云毅网络有限公司1 小时前
用 SQLite FTS5 给企业知识库做问答检索原型:中文二元切分与 BM25 排序
python·sqlite·自动化运维·geo·数据监测
承渊政道1 小时前
PR-Agent鸿蒙PC适配全记录:从Python服务端代理到ArkTS原生评审客户端
python·华为·代理模式·agent·harmonyos·pc端
Thomas.Sir1 小时前
第49课:TensorFlow|项目性能调优全方案【训练提速、推理提速、资源占用优化】
人工智能·python·tensorflow