如何使用Python导出Excel文件?

2024-03-29 14:02:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用Python导出Excel文件。我正在发送csv数据到我的代码和制作Excel文件。文件已成功保存到特定位置,并带有数据。但它不显示为下载,所以用户知道文件是下载的。在

有一些额外的代码可以对Excel工作表中的某些列进行验证:

def downloadUploadExclusionDetailReport(request):
    csv_data=request.GET.get('csv_data')
    createExcel(csv_data)
    return HttpResponse(csv_data, content_type="application/text")      

def createExcel(data):
    wb=openpyxl.Workbook()
    WorkSheet=wb.create_sheet(title="report")
    data=data.split('|')
    row_count=1
    col_count=1
    for row in data:
        row=row.split(',')
        col_count=1
        for cell in row:
            WorkSheet.cell(row=row_count, column=col_count).value=cell
            col_count=col_count+1
        row_count=row_count+1
    ########Add Checked / Unchecked 
    dv1 = DataValidation(type="list", formula1='"checked,unchecked"', allow_blank=False)
    # Optionally set a custom error message
    dv1.error ='Your entry is not in the list'
    dv1.errorTitle = 'Invalid Entry'
    # Optionally set a custom prompt message
    dv1.prompt = 'Please select from the list'
    dv1.promptTitle = 'List Selection'
    # Add the data-validation object to the worksheet
    WorkSheet.add_data_validation(dv1)
    dv1.ranges.append('A2:A1048576')

    ########Add Exclusion Reason List
    dv2 = DataValidation(type="list", formula1='"limited_by_machine_size,fixed_cycle_time,moq_cannot_be_renegotiated,lt_cannot_be_renegotitaed,vendor_refused_to_be_vendor_consignment,quality_issue_dont_have_short_term_solution,fix_import_export_time,special_requirement_from_customer,new_product,others"', allow_blank=True)
    # Optionally set a custom error message
    dv2.error ='Your entry is not in the list'
    dv2.errorTitle = 'Invalid Entry'
    # Optionally set a custom prompt message
    dv2.prompt = 'Please select from the list'
    dv2.promptTitle = 'List Selection'
    # Add the data-validation object to the worksheet
    WorkSheet.add_data_validation(dv2)
    dv2.ranges.append('B2:B1048576')

    ########Add Action Category List
    dv3 = DataValidation(type="list", formula1='"Max_Benefit,MTO-MTS,Vendor_Consignment,Lead_Time,Prod_Cycle_Time,MOQ,Batch_Size,Quality_Issue"', allow_blank=True)
    # Optionally set a custom error message
    dv3.error ='Your entry is not in the list'
    dv3.errorTitle = 'Invalid Entry'
    # Optionally set a custom prompt message
    dv3.prompt = 'Please select from the list'
    dv3.promptTitle = 'List Selection'
    # Add the data-validation object to the worksheet
    WorkSheet.add_data_validation(dv3)
    dv3.ranges.append('C2:C1048576')

    wb.save('C:\Python27\henkel_supply_chain\\fuploads\Template Ver 2.xlsx')

Tags: theaddmessagedatacountcustomerrorprompt