xlrd读excel

发布时间 2023-06-25 11:50:16作者: 小张爱炼丹

xlrd模块

import xlrd

# 获取Excel文件对象
workbook = xlrd.open_workbook(filename = "文件路径")

# 根据索引获取sheet对象
sheet = workbook.sheets()[0]

# sheet的行数
sheet.nrows

# sheet的列数
shhet.ncols

# 获取指定行的数据
# rowx表示获取第几行的数据,start_colx表示从多少列开始,end_colx表示从多少列结束
sheet_list = sheet.row_values(rowx=0, start_colx=0, end_colx=None)

# 获取指定单元格内容的类型
# ctype: 0-empty, 1-string, 2-number, 3-date, 4-boolean, 5-error
print(sheet1.cell(row,col).ctype)
# 暴力读公司名和总数
def excel_to_db(request):
    workbook = xlrd.open_workbook(filename="app01/state/data/data.xls")
    # 读到产品的sheet
    sheet = workbook.sheets()[1]
    rows = sheet.nrows
    cols = sheet.ncols
    # 读表格数据,并写入Company表
    for item in range(1, rows):
        company = models.Company()
        if sheet.cell(item, 0).ctype != 0:
            if sheet.cell(item, 0).value != "SUM":
                # 公司名称写入数据库表
                company.name = sheet.cell(item, 0).value
                print(sheet.cell(item, 0).value)
            elif sheet.cell(item, 0).value == "SUM":
                # 公司总产品数写入数据表
                company.product_num = int(sheet.cell(item, 6).value)
        company.save()
    return HttpResponse("测试成功")