python讀取excel文件


 

# 最近寫項目需要,通過讀取excel文件導入數據至數據庫

 

第一種方式: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)

 

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM