我正在我的 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()
关于django - 使用 xlswriter || 自动调整列宽 Django ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60345896/