Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
478 views
in Technique[技术] by (71.8m points)

python - Adjust cell width in 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()

What I am getting

enter image description here

What I am expecting with adjusted widths

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could use set_column as follows:

worksheet1.set_column(1, 1, 25)

This is defined as follows:

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. Also consider if a proportional or fixed width font is used.

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()

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...