在Excel中调整单元格宽度 [英] Adjust cell width in Excel
问题描述
我正在使用xlsxwriter写入Excel工作表.我面临的问题是:当文本多于单元格大小时,它将被隐藏.
I am using xlsxwriter to write into Excel sheet. I am facing issue: when text is more then cell size it's getting hidden.
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()
我得到的东西
宽度调整后的期望值
推荐答案
You could use set_column
as follows:
worksheet1.set_column(1, 1, 25)
定义如下:
set_column(first_col, last_col, width, cell_format, options)
您可能需要根据整个列中最长的文本长度来确定合适的宽度.不过,需要根据所使用的字体和大小来谨慎.
You would need to determine a suitable width, perhaps based on the longest length of text in the whole column. Care though would be needed to base this on the font and size being used.
如果要自动自动适应所有列,而不考虑字体和大小,则需要使用win32com
界面,如下所示:
If you want to autofit all of the columns automatically regardless of the font and size, then you will need to use the win32com
interface as follows:
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()
使用当前的xlsxwriter代码关闭文件后,可以轻松完成此操作.请注意,您可能需要提供文件的完整路径.
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.
这篇关于在Excel中调整单元格宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!