Adjust cell width in Excel

后端 未结 2 847
温柔的废话
温柔的废话 2020-12-01 08:10

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 =          


        
2条回答
  •  死守一世寂寞
    2020-12-01 08:31

    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.

提交回复
热议问题