python3讀取excel表數(shù)據(jù)(可指定sheet表讀取及設(shè)置讀取后返回的數(shù)據(jù)類型)

1、前述介紹

我在測(cè)試一個(gè)智能對(duì)話項(xiàng)目時(shí)需要評(píng)估對(duì)話的準(zhǔn)確率,就設(shè)計(jì)了一些問題放到excel表中,讀取問題并觸發(fā)問答后把響應(yīng)信息按需要的數(shù)據(jù)寫入到另外一個(gè)excel中?;谶@個(gè),我分別寫了讀excel函數(shù)和寫excel函數(shù)。
使用方法、注意事項(xiàng)、參數(shù)介紹等均在源碼中有注釋,不在這里贅述,下面直接看源碼。

寫excel表文章地址:http://www.itdecent.cn/p/8843cefc1cd2

2、源碼

# 讀excel文件
def readExcel(readExcelNameOrPath='', readSheets=None, contentType='json'):
    import xlrd, os, json
    # 參數(shù)說明
    # readExcelNameOrPath  讀取excel的文件名稱(aa.xls)或文件的絕對(duì)路徑(r"E:\test\aa.xls"),如果為文件名稱,必須放到當(dāng)前目錄下
    # readSheets   要讀取的sheet表名稱,如果不設(shè)置默認(rèn)讀取第一個(gè)表,如果設(shè)置為all代表讀取全部的sheet的內(nèi)容,注意:只有['all']這種情況下才讀取全部sheet
    # contentType   設(shè)置返回值的類型
    # 注意:如果路徑中出現(xiàn)轉(zhuǎn)義字符,如\t,\n等,路徑前面加r,如 r"E:\test\aa.xls"
    # 返回值格式:{sheetName:[{"row": 0, "col": 0, "content": content}, ..., {"row": m, "col": n, "content": content}]}

    readExcelNameOrPath = str(readExcelNameOrPath)
    contentType = str(contentType).lower()
    readSheetsContent = {}  # key為sheet表名稱,value為對(duì)應(yīng)sheet的內(nèi)容list
    readSheetsInfoList = []

    try:
        # 處理傳參錯(cuò)誤時(shí)的情況
        if not os.path.isfile(os.path.abspath(readExcelNameOrPath)):
            readSheetsContent['文件錯(cuò)誤'] = '文件名稱或路徑設(shè)置錯(cuò)誤[%s]' % (readExcelNameOrPath, )
            readSheetsContent['規(guī)則'] = '只設(shè)置文件名稱,需要將文件放到當(dāng)前目錄下;如果設(shè)置路徑,必須為文件的絕對(duì)路徑,如%s' % (r"E:\test\aa.xls", )
            if contentType != 'dict':
                readSheetsContent = json.dumps(readSheetsContent, ensure_ascii=False)
            return readSheetsContent
        if not (os.path.abspath(readExcelNameOrPath).endswith('.xls') or os.path.abspath(readExcelNameOrPath).endswith('.xlsx')):
            readSheetsContent['文件錯(cuò)誤'] = ' 文件格式錯(cuò)誤,必須為excel文件,后綴名只能為.xls和.xlsx'
            if contentType != 'dict':
                readSheetsContent = json.dumps(readSheetsContent, ensure_ascii=False)
            return readSheetsContent
        # 打開文件
        excelInfo = xlrd.open_workbook(readExcelNameOrPath)

        # 需要讀取的sheet表參數(shù)傳參異常時(shí)默認(rèn)讀取第一個(gè)
        if not isinstance(readSheets, list) or not readSheets:
            temSheet = excelInfo.sheet_by_index(0)
            readSheetsInfoList.append(temSheet)
        else:
            # 如果設(shè)置為all,處理全部sheet表格
            if len(readSheets) == 1 and str(readSheets[0]).lower() == 'all':
                for sheetIndex in range(0, excelInfo.nsheets):
                    temSheet = excelInfo.sheet_by_index(sheetIndex)
                    readSheetsInfoList.append(temSheet)

            # 按設(shè)置的sheet表名稱進(jìn)行處理
            else:
                for sheetName in readSheets:
                    sheetName = str(sheetName)
                    try:
                        temSheet = excelInfo.sheet_by_name(sheetName)
                        readSheetsInfoList.append(temSheet)
                    except:
                        # sheet表名稱找不到時(shí)返回提示信息,注意:區(qū)分大小寫
                        readSheetsContent[sheetName] = ['該sheet表不存在']

        # 開始處理sheet表數(shù)據(jù)
        for sheetInfo in readSheetsInfoList:
            dataRows = sheetInfo.nrows
            dataCols= sheetInfo.ncols
            if dataRows > 0:
                temDict = []
                for row in range(0, dataRows):
                    for col in range(0, dataCols):
                        temD = {}
                        temD['row'] = row + 1
                        temD['col'] = col + 1
                        temD['content'] = sheetInfo.cell_value(row, col)
                        temDict.append(temD)
                readSheetsContent[sheetInfo.name] = temDict
            else:
                readSheetsContent[sheetInfo.name] = []

        # 處理返回結(jié)果的數(shù)據(jù)類型,字典或json
        if contentType != 'dict':
            readSheetsContent = json.dumps(readSheetsContent, ensure_ascii=False)
        return readSheetsContent
    except Exception as e:
        return e

3、調(diào)用及結(jié)果(三種情況,只設(shè)置了json格式,字典格式將json換成dict即可)

數(shù)據(jù)源截圖:


Sheet2.png
測(cè)試1.png
測(cè)試2.png

3.1 正常讀取-全部sheet

if __name__ == '__main__':
    testRead = readExcel(readExcelNameOrPath=r'E:\test\mytest\aa.xls', readSheets=['all'], contentType='json')
    print(testRead)

結(jié)果1-正常讀取-全部
{"測(cè)試1": [{"row": 1, "col": 1, "content": ""}, {"row": 1, "col": 2, "content": ""}, {"row": 2, "col": 1, "content": "我在第3行第2列"}, {"row": 2, "col": 2, "content": ""}, {"row": 3, "col": 1, "content": ""}, {"row": 3, "col": 2, "content": "我在第5行第3列"}], "Sheet2": [{"row": 1, "col": 1, "content": "我在第1行第1列"}, {"row": 1, "col": 2, "content": "我在第1行第2列"}, {"row": 2, "col": 1, "content": "我在第2行第1列"}, {"row": 2, "col": 2, "content": "我在第2行第2列"}, {"row": 3, "col": 1, "content": "我在第3行第1列"}, {"row": 3, "col": 2, "content": "我在第3行第2列"}, {"row": 4, "col": 1, "content": "我在第4行第1列"}, {"row": 4, "col": 2, "content": "我在第4行第2列"}, {"row": 5, "col": 1, "content": ""}, {"row": 5, "col": 2, "content": ""}, {"row": 6, "col": 1, "content": ""}, {"row": 6, "col": 2, "content": "我在第6行第2列"}, {"row": 7, "col": 1, "content": ""}, {"row": 7, "col": 2, "content": "我在第7行第2列"}], "測(cè)試2": ["空表"]}

轉(zhuǎn)為格式化展示如下:
{
    "測(cè)試1":[
        {
            "row":1,
            "col":1,
            "content":""
        },
        {
            "row":1,
            "col":2,
            "content":""
        },
        {
            "row":2,
            "col":1,
            "content":"我在第3行第2列"
        },
        {
            "row":2,
            "col":2,
            "content":""
        },
        {
            "row":3,
            "col":1,
            "content":""
        },
        {
            "row":3,
            "col":2,
            "content":"我在第5行第3列"
        }
    ],
    "Sheet2":[
        {
            "row":1,
            "col":1,
            "content":"我在第1行第1列"
        },
        {
            "row":1,
            "col":2,
            "content":"我在第1行第2列"
        },
        {
            "row":2,
            "col":1,
            "content":"我在第2行第1列"
        },
        {
            "row":2,
            "col":2,
            "content":"我在第2行第2列"
        },
        {
            "row":3,
            "col":1,
            "content":"我在第3行第1列"
        },
        {
            "row":3,
            "col":2,
            "content":"我在第3行第2列"
        },
        {
            "row":4,
            "col":1,
            "content":"我在第4行第1列"
        },
        {
            "row":4,
            "col":2,
            "content":"我在第4行第2列"
        },
        {
            "row":5,
            "col":1,
            "content":""
        },
        {
            "row":5,
            "col":2,
            "content":""
        },
        {
            "row":6,
            "col":1,
            "content":""
        },
        {
            "row":6,
            "col":2,
            "content":"我在第6行第2列"
        },
        {
            "row":7,
            "col":1,
            "content":""
        },
        {
            "row":7,
            "col":2,
            "content":"我在第7行第2列"
        }
    ],
    "測(cè)試2":[
        "空表"
    ]
}

3.2 正常讀取-指定sheet

if __name__ == '__main__':
    testRead = readExcel(readExcelNameOrPath=r'E:\test\mytest\aa.xls', readSheets=['Sheet2','測(cè)試2'], contentType='json')
    print(testRead)

結(jié)果2-正常讀取-指定sheet
{"Sheet2": [{"row": 1, "col": 1, "content": "我在第1行第1列"}, {"row": 1, "col": 2, "content": "我在第1行第2列"}, {"row": 2, "col": 1, "content": "我在第2行第1列"}, {"row": 2, "col": 2, "content": "我在第2行第2列"}, {"row": 3, "col": 1, "content": "我在第3行第1列"}, {"row": 3, "col": 2, "content": "我在第3行第2列"}, {"row": 4, "col": 1, "content": "我在第4行第1列"}, {"row": 4, "col": 2, "content": "我在第4行第2列"}, {"row": 5, "col": 1, "content": ""}, {"row": 5, "col": 2, "content": ""}, {"row": 6, "col": 1, "content": ""}, {"row": 6, "col": 2, "content": "我在第6行第2列"}, {"row": 7, "col": 1, "content": ""}, {"row": 7, "col": 2, "content": "我在第7行第2列"}], "測(cè)試2": ["空表"]}

轉(zhuǎn)為json格式化展示如下:
{
    "Sheet2":[
        {
            "row":1,
            "col":1,
            "content":"我在第1行第1列"
        },
        {
            "row":1,
            "col":2,
            "content":"我在第1行第2列"
        },
        {
            "row":2,
            "col":1,
            "content":"我在第2行第1列"
        },
        {
            "row":2,
            "col":2,
            "content":"我在第2行第2列"
        },
        {
            "row":3,
            "col":1,
            "content":"我在第3行第1列"
        },
        {
            "row":3,
            "col":2,
            "content":"我在第3行第2列"
        },
        {
            "row":4,
            "col":1,
            "content":"我在第4行第1列"
        },
        {
            "row":4,
            "col":2,
            "content":"我在第4行第2列"
        },
        {
            "row":5,
            "col":1,
            "content":""
        },
        {
            "row":5,
            "col":2,
            "content":""
        },
        {
            "row":6,
            "col":1,
            "content":""
        },
        {
            "row":6,
            "col":2,
            "content":"我在第6行第2列"
        },
        {
            "row":7,
            "col":1,
            "content":""
        },
        {
            "row":7,
            "col":2,
            "content":"我在第7行第2列"
        }
    ],
    "測(cè)試2":[
        "空表"
    ]
}

3.3 文件設(shè)置錯(cuò)誤

if __name__ == '__main__':
    testRead = readExcel(readExcelNameOrPath=r'hello', readSheets=['all'], contentType='json')
    print(testRead)

結(jié)果3-文件設(shè)置錯(cuò)誤
{"文件錯(cuò)誤": "文件名稱或路徑設(shè)置錯(cuò)誤[hello]", "規(guī)則": "只設(shè)置文件名稱,需要將文件放到當(dāng)前目錄下;如果設(shè)置路徑,必須為文件的絕對(duì)路徑,如E:\\test\\aa.xls"}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容