使用xlswriter自动调整列宽|| Django

问题描述 投票:0回答:2

我在Django views.py中生成excel,但是由于列名有点长,我每次都很难手动设置自动列适合宽度我/用户下载了excel 。

下面是我使用xlswriter生成excel的工作代码段。

def excel(request):
    ans = request.POST.getlist('ans[]')
    ans_final=[]
    rows = request.POST.get('rows')
    for each_ele in ans:
        each_ele = each_ele.split('.')
        each_ele[0] = each_ele[0][:-2]
        each_ele[1] = each_ele[1][:-2]
    fin = each_ele[0]+' - '+each_ele[1]
    ans_final.append(fin)
    workbook = xlsxwriter.Workbook('/home/Desktop/status.xlsx')
    worksheet = workbook.add_worksheet('Test_Data')
    bold = workbook.add_format({'bold': True})
    for i in range(len(ans_final)):
        worksheet.write(0, i,ans_final[i],bold)

    row_index=1
    row_count = int(rows)
    while(row_count):
        col_index=0
        for each_ele in ans:
            worksheet.write(row_index, col_index, eval(each_ele))
            col_index += 1
        row_index += 1
        row_count -= 1


   workbook.close() 
   return JsonResponse({'ok':'ok'})

请在上面的代码中建议设置自动调整列宽的解决方法。

django python-3.x xlsxwriter column-width
2个回答
0
投票

您可以尝试使用worksheet.set_column(<start_col>, <end_col>, <width>)功能吗?

或者,如果您希望它自动正确地自动适应,我认为您需要win32com库?

在将数据添加并保存到电子表格后,您必须运行类似的内容:

import win32com.client as win32_client
excel_application = win32_client.gencache.EnsureDispatch('Excel.Application')
workbook = excel_application.Workbooks.Open(`<path_to_file>`)
worksheet = workbook.Worksheets("Test_Data")
worksheet.Columns.AutoFit()
workbook.Save()
excel_application.Application.Quit()

0
投票

[遗憾的是,无法为Excel文件格式的列指定“自动调整”。此功能仅在运行时从Excel内可用。通过在写入时跟踪列中数据的最大宽度,然后在末尾调整列宽,可以在应用程序中模拟“自动调整”。从文档中的FAQ

您可以在向列内写入数据时更新代码并跟踪列数据长度。这将进入您的while循环内。

def excel(request):
    ans = request.POST.getlist('ans[]')
    ans_final=[]
    rows = request.POST.get('rows')
    for each_ele in ans:
        each_ele = each_ele.split('.')
        each_ele[0] = each_ele[0][:-2]
        each_ele[1] = each_ele[1][:-2]
    fin = each_ele[0]+' - '+each_ele[1]
    ans_final.append(fin)
    workbook = xlsxwriter.Workbook('/home/Desktop/status.xlsx')
    worksheet = workbook.add_worksheet('Test_Data')
    bold = workbook.add_format({'bold': True})
    for i in range(len(ans_final)):
        worksheet.write(0, i,ans_final[i],bold)

    row_index=1
    row_count = int(rows)
    cell_width = {}
    while(row_count):
        col_index=0
        for each_ele in ans:
            cell = worksheet.cell(row_index, col_index)
            cell.value = eval(each_ele)
            if cell.column_letter in cell_width:
                cell_width[cell.column_letter].append(len(eval(each_ele)))
            else:
                cell_width[cell.column_letter] = [len(cell_value[0])]
            col_index += 1
        row_index += 1
        row_count -= 1

    for key in cell_width.keys():
        width  = max(cell_width[key])
        worksheet.column_dimensions[key].width = width + 5

   workbook.close() 
   return JsonResponse({'ok':'ok'})

这里,我将每个值的长度保留在列表中,然后获取最大数量,然后将其设置为列宽。我要添加5,以在内容之后添加一些额外的空间。我希望这能帮到您。 :)

© www.soinside.com 2019 - 2024. All rights reserved.