python讀取excel數據轉爲json格式

作自動化時須要從excel讀取數據;
本文實現將excel文件數據讀取爲json格式,方便自動化調用

讀取xls文件

使用xlrd讀取xls文件代碼:python

import xlrd


def read_xls(file):
    # 實例化excel
    book = xlrd.open_workbook(file)
    # 下標讀取sheet
    sheet = book.sheet_by_index(1)
    # sheet name讀取sheet
    # sheet = book.sheet_by_name('Sheet1')
    # 獲取總行數
    nrows = sheet.nrows
    # 循環讀取每行數據
    datas = []
    for i in range(1, nrows):
        # print(sheet.row_values(i))
        # 數據組裝dic+t格式
        data = dict(zip(sheet.row_values(0), sheet.row_values(i)))
        datas.append(data)
    return datas

讀取xlsx文件

由於xlrd只能讀取xls,如遇到xlsx文件,須要使用openpyxl庫讀取,代碼以下:json

from openpyxl import load_workbook
def read_xlsx(file):
    # 加載文件
    book = load_workbook(file)
    # sheet name獲取sheet:
    sheet = book['sheet1']
    # 獲取總行數
    rows = sheet.max_row
    # 獲取總列數
    # cols = sheet.max_column
    # print(rows)
    # 獲取表頭
    head = [row for row in sheet.iter_rows(min_row=1, max_row=1, values_only=True)][0]
    # 數據組裝
    datas = []
    for row in sheet.iter_rows(min_row=2, max_row=rows + 1, values_only=True):
        data = dict(zip(head, row))
        datas.append(data)
    # print(datas)
    return datas

判斷文件類型方法

最後根據文件後綴自動選擇對應方法讀取segmentfault

def read_excel(file: str):
    if file.endswith('xls'):
        data = read_xls(file)
    elif file.endswith('xlsx'):
        data = read_xlsx(file)
    else:
        data = ['not support file']
    return data

最終代碼

import xlrd
from openpyxl import load_workbook


def read_xls(file):
    # 實例化excel
    book = xlrd.open_workbook(file)
    # 下標讀取sheet
    sheet = book.sheet_by_index(1)
    # sheet name讀取sheet
    # sheet = book.sheet_by_name('Sheet1')
    # 獲取總行數
    nrows = sheet.nrows
    # 循環讀取每行數據
    datas = []
    for i in range(1, nrows):
        # print(sheet.row_values(i))
        # 數據組裝dic+t格式
        data = dict(zip(sheet.row_values(0), sheet.row_values(i)))
        datas.append(data)
    return datas


def read_xlsx(file):
    # 加載文件
    book = load_workbook(file)
    # sheet name獲取sheet:
    sheet = book['sheet1']
    # 獲取總行數
    rows = sheet.max_row
    # 獲取總列數
    # cols = sheet.max_column
    # print(rows)
    # 獲取表頭
    head = [row for row in sheet.iter_rows(min_row=1, max_row=1, values_only=True)][0]
    # 數據組裝
    datas = []
    for row in sheet.iter_rows(min_row=2, max_row=rows + 1, values_only=True):
        data = dict(zip(head, row))
        datas.append(data)
    # print(datas)
    return datas
    # 獲取單元格值:
    # Data = sheet.cell(row=row, column=col).value  # 獲取表格內容,是從第一行第一列是從1開始的,注意不要丟掉 .value


def read_excel(file: str):
    if file.endswith('xls'):
        data = read_xls(file)
    elif file.endswith('xlsx'):
        data = read_xlsx(file)
    else:
        data = ['not support file']
    return data

End
流柯 https://segmentfault.com/u/cnliukeapp

相關文章
相關標籤/搜索