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
相关推荐
IT空门:门主2 小时前
Spring AI 2.1.0 更新了什么:从 2.0 升上来的完整梳理
人工智能·python·spring
AI创界者3 小时前
Python 进阶实战(七十章):遗留系统重构、渐进式绞杀与技术债治理实战
人工智能·python·aigc
ZhengEnCi4 小时前
电脑操作 Agent 一直点不中:截图没更新时,提示词该怎么改才能停止瞎试
人工智能·python·agent
Wellijohn5 小时前
dict、tuple、dataclass 还是 slots?我把 6 种数据载体的 8 项开销全测了一遍
后端·python·性能优化
bufengwangluo6 小时前
爬虫和调用 API 有什么区别?为什么优先选 API
python·网络爬虫·ip·api调用
Dmz丶6 小时前
前端转 AI 100 天 Day 54:RAG 项目实战(三)——多轮对话 + 会话管理
python
console.log('npc')7 小时前
Python第9课 类学习笔记,前端js语法对照
前端·python·学习
geovindu8 小时前
python:Logistic Regression
开发语言·后端·python·算法
geovindu10 小时前
python: Random Forest
开发语言·后端·python·算法·随机森林