http requests the excel file generated by Django to the browser and receives it locally

The code for Django to generate an excel file is as follows:

1. Generate headers and create file information

        import xlsxwriter #module import 
filename = 'file.xlsx' filepath = '/tmp/{0}'.format(filename) #Temporary storage file location workbook = xlsxwriter.Workbook(filepath) worksheet = workbook.add_worksheet() #Create a workbook row = 0 top = workbook.add_format( {'border': 1, 'align': 'center', 'bg_color': 'cccccc', 'font_size': 13, 'bold': True}) #Create title name and background color top_list = [ 'user', 'password', 'Mail', 'content', ] #content for i, v in enumerate(top_list): #Generate with ordinal number plus content worksheet.write(row, i, v, top) #写入

2. Write the header content corresponding to the column

          event_ret=[['a1', 'b2', 'b3', 'c4'], ['a1', 'b2', 'b3', 'c4']] # Combine multiple lists as needed, just This content will be formed, and why it is written in this way is related to the following enumerate function
                ret = tuple(event_ret)#The list needs to be converted into a tuple tuple, and then the enumerate function is read for the first time to get multiple lists
                for i, v in enumerate(ret): #Read the first layer of tuples and loop in turn
                    for j, u in enumerate(v):#Read all lists below the first level
                        worksheet.write(i + 1, j, u) #Write i+1, write the next line of the title
                workbook.close()
                response = HttpResponse(open(filepath, 'rb'), content_type='application/vnd.ms-excel') #http return supports Microsoft excel
                response['Content-Disposition'] = 'attachment; filename="{0}";filename*=UTF-8\'\'{1}'.format(
                    urllib.parse.quote_plus(filename), urllib.parse.quote_plus(filename)) #To support IE, Firefox, Google browser, write method
                os.remove(filepath) #delete local files
                return response #After the file stream returns to the browser

Summarize

The above operating environment Python 3.6.3 Django 1.11.* version

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325053759&siteId=291194637