-1

I have dataframe (df) that is added to an existing excel file as a new tab ('Print'). I am having difficulties adjusting the column width any ideas?

Code

book = load_workbook('file.xlsx')
writer = pd.ExcelWriter('file.xlsx', engine = 'openpyxl')
writer.book = book
df.to_excel(writer,sheet_name = 'Print')
worksheet = writer.sheets['Print']
worksheet.set_column('B:B', 40) #This does not work
ms5573
  • 41
  • 5
  • Possible duplicate of [Adjust cell width in Excel](https://stackoverflow.com/questions/33665865/adjust-cell-width-in-excel) – Rahul Agarwal Aug 31 '18 at 14:31
  • If you are open to changing your engine to `'xlsxwriter'`, this blog post [Improving Pandas’s Excel Output](http://pbpython.com/improve-pandas-excel-output.html) answers your question nicely. – Steven Rumbalski Aug 31 '18 at 14:50

2 Answers2

0
writer = pd.ExcelWriter('file.xlsx', engine='openpyxl')
writer.book = book
df.to_excel(writer, sheet_name='Print')
sheet = book.get_sheet_by_name('Print')
sheet.column_dimensions['B'].width = 40
writer.save()
Steven Rumbalski
  • 44,786
  • 9
  • 89
  • 119
-2

I've never used nor done this, but I just googled for "worksheet.set_column" and found this: https://xlsxwriter.readthedocs.io/worksheet.html

The syntax for the function is

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

So I'd say the answer is:

worksheet.set_column(2, 2, 40)
JtenBulte
  • 36
  • 6