【问题标题】:autofit column width using xlswriter || Django使用 xlswriter 自动调整列宽 ||姜戈
【发布时间】:2020-06-06 07:27:57
【问题描述】:

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

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

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


【解决方案1】:

很遗憾,无法为 Excel 文件格式中的列指定“自动调整”。此功能仅在运行时从 Excel 中可用。通过在写入时跟踪列中数据的最大宽度,然后在最后调整列宽,可以在应用程序中模拟“AutoFit”。来自文档中的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 以在内容之后添加一些额外的空间。我希望这能帮到您。 :)

【讨论】:

    【解决方案2】:

    您可以尝试使用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()
    

    【讨论】:

      猜你喜欢
      • 2020-08-17
      • 1970-01-01
      • 1970-01-01
      • 2016-01-21
      • 2023-03-29
      • 2013-05-21
      • 2011-03-29
      • 2014-04-05
      相关资源
      最近更新 更多