首页 > 技术文章 > python读取excel文件

zezhou 2019-09-13 22:07 原文

 

第一种方式:xlrd方式

安装模块:

pip install xlrd

 

导入模块:

import xlrd

 

拿到操作excel句柄,读取excel文件:

workbook = xlrd.open_workbook(filepath)   # 硬盘读取

workbook = xlrd.open_workbook(file_contents=file.read())   # excel数据传入,excel数据不保存在本地时候使用

 

拿到sheet句柄:

(1) 通过索引获取sheet句柄(没有名称的用这个,一般我就一个sheet)

sheet = workbook.sheet_by_index(0)

 

(2) 通过sheet名获取sheet句柄

sheet = workbook.sheet_by_name(sheetname)

# 没找到会报错xlrd.biffh.XLRDError: No sheet named <'sheet那个名称'> 

 

sheet指的是这个:

 

获取第一行数据:

rows = sheet.row_values(0)

print(rows)

 

获取总行数:

print(sheet.nrows)

 

组合起来的写法:

import xlrd

def read_excel_data(filepath):
    
    workbook = xlrd.open_workbook(filepath)

    sheet = workbook.sheet_by_index(0)

    for index in range(1, sheet.nrows):

        row_value = sheet.row_values(index)

        print(row_value)


if __name__ == '__main__':
read_excel_data(
'test.xlsx')

 

前端文件形式发送,后端内存读取excel数据:

def answer_upload(req, kf_type):
    import xlrd
    file = req.FILES.get('file')
    workbook = xlrd.open_workbook(file_contents=file.read())
    sheet = workbook.sheet_by_index(0)
    objs = []
    for index in range(3, sheet.nrows):
        row_value = sheet.row_values(index)
        obj = Answer(keyword_name=row_value[0], answer=row_value[1], kf_type=kf_type)
        objs.append(obj)
    Answer.objects.bulk_create(objs)

    res = {"status": 0, "message": "%s上传成功!" % file.name}
    return HttpResponse(json.dumps(res))

# 重点是xlrd.open_workbook得file_contents属性

 

第二种方式:pandas

安装模块:

pip install pandas -i https://pypi.tuna.tsinghua.edu.cn/simple

 

导入模块:

import pandas as pd

 

读取文件:

data = pd.read_excel(io=file_path, sheet_index=0, header=0)

# io 表示excel文件路径
# sheet_index 表示读取第几个sheet,sheet_name可指定名称,默认0
# header 表示表头最后是第几行,读取数据掠过表头数据用,默认为0第一行掠过去

 

查看行数:

len(data)

 

读取数据:

data.values[0]  # 表示拿出第一行数据,不包含表头

 

命令行可视化表格:

data.head()

 

 

例子写法:

import pandas as pd

file_path = './test.xlsx'

data = pd.read_excel(io=file_path, sheet_index=0, header=0)

for ele in data.values:  # data.values二维数组形式
    print(ele[0], ele[1], ele[2])

 

推荐阅读