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

我正在我的 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'})

请建议在上述代码中设置自动调整列宽

最佳答案

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

https://stackoverflow.com/questions/60345896/

相关文章:

python - 由于自定义度量函数,Keras 中出现无效的磁带状态错误

nginx - Flask Mail 在 Ubuntu 上部署时不起作用

python - API错误异常: (BadArgument) 'recognitionModel'

node.js - 错误 "Your cache folder contains root-owne

git - 当我提交 Git 时,找不到 cmd.exe

python - 使用 PIL 合并图像时模式不匹配

angular - 使用 GitHub Actions 运行 Angular e2e 测试会抛出 "

logging - 如何为 glib 调试日志添加文件名、行、函数前缀

python-3.x - 从目录流式传输图像并将预测与 tensorflow 中的文件名相关联

vue.js - 如何更新 vuetify mdi 图标? (Nuxt.js)