Python 在 Excel 中调整单元格宽度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33665865/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:44:18  来源:igfitidea点击:

Adjust cell width in Excel

pythonexcelxlsxwriter

提问by Ravichandra

I am using xlsxwriter to write into Excel sheet. I am facing issue: when text is more then cell size it's getting hidden.

我正在使用 xlsxwriter 写入 Excel 工作表。我面临的问题:当文本大于单元格大小时,它会被隐藏。

import xlsxwriter

workbook = xlsxwriter.Workbook("file.xlsx")
worksheet1 = workbook.add_worksheet()

worksheet1.write(1, 1,"long text hidden test-1" )
worksheet1.write(2, 1,"long text hidden test-2")
worksheet1.write(3, 1,"short-1")
worksheet1.write(4, 1,"short-2")
worksheet1.write(1, 2,"Hello world" )
worksheet1.write(2, 2,"Hello world")
worksheet1.write(3, 2,"Hello world")
worksheet1.write(4, 2,"Hello world")

workbook.close()

What I am getting

我得到了什么

enter image description here

enter image description here

What I am expecting with adjusted widths

我对调整宽度的期望

enter image description here

enter image description here

回答by Martin Evans

You could use set_columnas follows:

你可以使用set_column如下:

worksheet1.set_column(1, 1, 25)

This is defined as follows:

这定义如下:

set_column(first_col, last_col, width, cell_format, options)

If you want to autofit all of the columns automatically, then you will need to use the win32cominterface as follows:

如果要自动调整所有列,则需要使用win32com如下界面:

import win32com.client as win32
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Open(r'file.xlsx')
ws = wb.Worksheets("Sheet1")
ws.Columns.AutoFit()
wb.Save()
excel.Application.Quit()

This can easily be done after you closed the file using your current xlsxwriter code. Note, you might need to supply a full path to your file.

这可以在您使用当前的 xlsxwriter 代码关闭文件后轻松完成。请注意,您可能需要提供文件的完整路径。

回答by Fahad Sarfraz

Unfortunately xlsxwriter doesnt provide autofit option.

不幸的是 xlsxwriter 不提供自动调整选项。

You can however track the largest entry for each column and then set the column width in the end with set column command.

但是,您可以跟踪每列的最大条目,然后最后使用 set column 命令设置列宽。

set_column(first_col, last_col, width, cell_format, options)

In your case for instance, you should set the width of B column to the length of the largest string.

例如,在您的情况下,您应该将 B 列的宽度设置为最大字符串的长度。

width= len("long text hidden test-1")
worksheet1.set_column(1, 1, width)