xlrd讀取excel時(shí),解決int、float變float問(wèn)題

1、導(dǎo)入需要的包

import xlrd
import datetime

2、編寫一個(gè)用于導(dǎo)入excel文件的裝飾器

# A decoration: import excel file
def import_excel_file(fn):
    @functools.wraps(fn)
    def wrapper(request, *args, **kwargs):
        # 檢查導(dǎo)入的文件請(qǐng)求是否合法,文件是否能收到
        try:
            excel = request.FILES['excel']
        except MultiValueDictKeyError:
            return render(request, '400.html', {
                'err': '數(shù)據(jù)導(dǎo)入出錯(cuò):沒(méi)有發(fā)現(xiàn)需要的導(dǎo)入的文件,請(qǐng)選擇導(dǎo)入的文件,再試一下!',
                'back_url': request.session.get('back_url')
            })
        except AttributeError:
            return render(request, '400.html', {
                'err': '數(shù)據(jù)導(dǎo)入出錯(cuò):request沒(méi)有excel參數(shù),請(qǐng)聯(lián)系管理員!',
                'back_url': request.session.get('back_url')
            })
        except KeyError:
            return render(request, '400.html', {
                'err': '數(shù)據(jù)導(dǎo)入出錯(cuò):request沒(méi)有excel參數(shù),請(qǐng)聯(lián)系管理員!',
                'back_url': request.session.get('back_url')
            })

        # 驗(yàn)證導(dǎo)入的文件是否為合法的表格文件
        try:
            validate_excel(excel)
        except ValidationError:
            return render(request, '400.html', {
                'err': '導(dǎo)入excel數(shù)據(jù)出錯(cuò):導(dǎo)入的文件< %s >格式不對(duì),請(qǐng)確保文件后綴是xls、xlsx 或csv!' % excel.name,
                'back_url': request.session.get('back_url')
            })
        else:
            data = xlrd.open_workbook(filename=None, file_contents=excel.read())
            table = data.sheets()[0]
            n_rows = table.nrows

            return fn(request, *args, **kwargs, table=table, n_rows=n_rows)

    return wrapper

3、編寫一個(gè)轉(zhuǎn)換單元格數(shù)據(jù)格式的工具函數(shù)

# A function tool: convert the type of cell while reading dates from import excel file
# Parameter: cell object which will be converted
# Return: right data type for python
def convert_cell_type_from_import_excel(_cell):
    # 單元格的ctype屬性為0時(shí),對(duì)應(yīng)的python格式為空字符串:''
    if _cell.ctype == 0:
        return ''

    # 單元格的ctype屬性為2時(shí),對(duì)應(yīng)的python格式為float和int
    # 手動(dòng)做以下判斷將int類型分離出來(lái)
    elif _cell.ctype == 2 and _cell.value % 1 == 0.0:
        return int(_cell.value)

    # 單元格的ctype屬性為3時(shí),對(duì)應(yīng)的python格式為datetime
    elif _cell.ctype == 3:
        return datetime.date(*xlrd.xldate_as_tuple(_cell.value, 0))

    # 單元格的ctype屬性為4時(shí),對(duì)應(yīng)的python格式為Bool
    elif _cell.ctype == 4:
        return True if _cell.value == 1 else False

    # 單元格的ctype屬性為1時(shí),對(duì)應(yīng)的python格式為字符串
    # 默認(rèn)返回字符串和ctype=2時(shí)的float類型的內(nèi)容
    else:
        return _cell.value

4、編寫實(shí)際讀取excel的處理函數(shù)(需用上述裝飾器進(jìn)行裝飾)

@import_excel_file
def import_product_standard(request, table=None, n_rows=None):

    for i in range(1, n_rows):
        try:
            # 使用工具函數(shù) "convert_cell_type_from_import_excel" 將每個(gè)cell對(duì)象轉(zhuǎn)換成相應(yīng)的Python格式
            dic = {'ps_name': str(convert_cell_type_from_import_excel(table.cell(i, 0))).strip()[:50],
                   'jspl': str(convert_cell_type_from_import_excel(table.cell(i, 1))).strip()[:50],
                   'wspl': str(convert_cell_type_from_import_excel(table.cell(i, 2))).strip()[:50],
                   'jsqsbs': str(convert_cell_type_from_import_excel(table.cell(i, 3))).strip()[:50],
                   'wsqsbs': str(convert_cell_type_from_import_excel(table.cell(i, 4))).strip()[:50],
                   'jsdskz': str(convert_cell_type_from_import_excel(table.cell(i, 5))).strip()[:50],
                   'wsdskz': str(convert_cell_type_from_import_excel(table.cell(i, 6))).strip()[:50],
                   'jsdsql': str(convert_cell_type_from_import_excel(table.cell(i, 7))).strip()[:50],
                   'wsdsql': str(convert_cell_type_from_import_excel(table.cell(i, 8))).strip()[:50],
                   'dbjxql': str(convert_cell_type_from_import_excel(table.cell(i, 9))).strip()[:50],
                   'dbwxql': str(convert_cell_type_from_import_excel(table.cell(i, 10))).strip()[:50],
                   'dbpfkz': str(convert_cell_type_from_import_excel(table.cell(i, 11))).strip()[:50],
                   'dbjm': str(convert_cell_type_from_import_excel(table.cell(i, 12))).strip()[:50],
                   'dbwm': str(convert_cell_type_from_import_excel(table.cell(i, 13))).strip()[:50]}
        ......
?著作權(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)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Swift1> Swift和OC的區(qū)別1.1> Swift沒(méi)有地址/指針的概念1.2> 泛型1.3> 類型嚴(yán)謹(jǐn) 對(duì)...
    cosWriter閱讀 11,619評(píng)論 1 32
  • 寫在前面的話 代碼中的# > 表示的是輸出結(jié)果 輸入 使用input()函數(shù) 用法 注意input函數(shù)輸出的均是字...
    FlyingLittlePG閱讀 3,202評(píng)論 0 9
  • 一點(diǎn)猩紅一寸光, 一卷殘霧費(fèi)思量。 又是深更夜半時(shí), 為誰(shuí)情癡為誰(shuí)傷。
    袁嘉軒閱讀 928評(píng)論 0 0
  • 大家好!我是玲瓏。80后,目前在一家剛剛事轉(zhuǎn)企的單位工作。 工作不忙,就是離家很遠(yuǎn),將近一千公里。兩個(gè)月回家一次,...
    玲瓏_5d16閱讀 500評(píng)論 0 11

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