xlrd读取excel时,解决int、float变float问题

1、导入需要的包

import xlrd
import datetime

2、编写一个用于导入excel文件的装饰器

# A decoration: import excel file
def import_excel_file(fn):
    @functools.wraps(fn)
    def wrapper(request, *args, **kwargs):
        # 检查导入的文件请求是否合法,文件是否能收到
        try:
            excel = request.FILES['excel']
        except MultiValueDictKeyError:
            return render(request, '400.html', {
                'err': '数据导入出错:没有发现需要的导入的文件,请选择导入的文件,再试一下!',
                'back_url': request.session.get('back_url')
            })
        except AttributeError:
            return render(request, '400.html', {
                'err': '数据导入出错:request没有excel参数,请联系管理员!',
                'back_url': request.session.get('back_url')
            })
        except KeyError:
            return render(request, '400.html', {
                'err': '数据导入出错:request没有excel参数,请联系管理员!',
                'back_url': request.session.get('back_url')
            })

        # 验证导入的文件是否为合法的表格文件
        try:
            validate_excel(excel)
        except ValidationError:
            return render(request, '400.html', {
                'err': '导入excel数据出错:导入的文件< %s >格式不对,请确保文件后缀是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、编写一个转换单元格数据格式的工具函数

# 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时,对应的python格式为空字符串:''
    if _cell.ctype == 0:
        return ''

    # 单元格的ctype属性为2时,对应的python格式为float和int
    # 手动做以下判断将int类型分离出来
    elif _cell.ctype == 2 and _cell.value % 1 == 0.0:
        return int(_cell.value)

    # 单元格的ctype属性为3时,对应的python格式为datetime
    elif _cell.ctype == 3:
        return datetime.date(*xlrd.xldate_as_tuple(_cell.value, 0))

    # 单元格的ctype属性为4时,对应的python格式为Bool
    elif _cell.ctype == 4:
        return True if _cell.value == 1 else False

    # 单元格的ctype属性为1时,对应的python格式为字符串
    # 默认返回字符串和ctype=2时的float类型的内容
    else:
        return _cell.value

4、编写实际读取excel的处理函数(需用上述装饰器进行装饰)

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

    for i in range(1, n_rows):
        try:
            # 使用工具函数 "convert_cell_type_from_import_excel" 将每个cell对象转换成相应的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]}
        ......
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,171评论 1 32
  • 写在前面的话 代码中的# > 表示的是输出结果 输入 使用input()函数 用法 注意input函数输出的均是字...
    FlyingLittlePG阅读 3,055评论 0 9
  • 参加东逸湾展览
    山野印象阅读 296评论 0 0
  • 一点猩红一寸光, 一卷残雾费思量。 又是深更夜半时, 为谁情痴为谁伤。
    袁嘉轩阅读 818评论 0 0
  • 大家好!我是玲珑。80后,目前在一家刚刚事转企的单位工作。 工作不忙,就是离家很远,将近一千公里。两个月回家一次,...
    玲珑_5d16阅读 491评论 0 11