问题
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
What I am expecting with adjusted widths
回答1:
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)
If you want to autofit all of the columns automatically, 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.
回答2:
Unfortunately xlsxwriter doesnt provide autofit option.
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(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.
width= len("long text hidden test-1")
worksheet1.set_column(1, 1, width)
来源:https://stackoverflow.com/questions/33665865/adjust-cell-width-in-excel