Django使用openpyxl导入excel文件

时间:2018-01-15 19:44:10

标签: django excel

我想在我的模型中添加一个excel文件 我的视图代码是这样的,使用openpyxl:

def excel_import(request):
uploadform=UploadFileForm(None)
if request.method == 'POST' :
    uploadform = UploadFileForm(request.POST, request.FILES)
    if uploadform.is_valid():
        file = uploadform.cleaned_data['docfile']
        workbook = openpyxl.load_workbook(filename=file, read_only=True)

        first_sheet = workbook.get_sheet_names()[0]
        worksheet = workbook.get_sheet_by_name(first_sheet)

        data = []

        for row in worksheet.iter_rows(row_offset=1): # Offset for header

                stock = Stocks()
                stock.user = request.user
                stock.name = row[0].value
                stock.number = row[1].value
                stock.suffix = row[2].value
                stock.brand = row[3].value
                stock.comment = row[4].value
                stock.price = row[5].value
                stock.date = datetime.today()
                stock.confirm = 'approved'
                stock.seller = row[7].value
                data.append(stock)

            # Bulk create data
        Stocks.objects.bulk_create(data)


return render(request, 'BallbearingSite/news.html',{'uploadform':uploadform})
问题是它为数据库添加了一些额外的空行。 代码有什么问题?我该如何解决?

1 个答案:

答案 0 :(得分:0)

我认为它在停止之前会在Excel中变成空白行。获取最后一行的编号。

wb=Workbook()
ws=wb.active
last_row=ws.max_row

现在使用last_row作为最大数量循环运行excel文件