I've been trying to autofit the column width of some excel workbooks. I found this thread: openpyxl - adjust column width size And tried to use most of these methods, but none worked. I didn't get any errors, but it also wasn't creating the result I had hoped for. What would I need to do or change to autofit, or change the width of my columns so that all the text is immediately readable without having to resize the columns manually.
Thanks!
from openpyxl.utils import get_column_letter
import openpyxl
files = ['A.xlsx', 'B.xlsx', 'C.xlsx', 'D.xlsx', 'E.xlsx']
for file in files:
wb = openpyxl.load_workbook('exported_data/' + file)
for sheet in range(len(wb.worksheets)):
ws = wb.worksheets[sheet]
for i in range(1, ws.max_column + 1):
ws.column_dimensions[get_column_letter(i)].bestFit = True
ws.column_dimensions[get_column_letter(i)].auto_size = True
Edit:
Problem solved! In case people find this when trying to solve a similar problem, I used xlwings as BigBen suggested in the comments. This is the code I ended up using:
import xlwings as xw
files = ['A.xlsx', 'B.xlsx', 'C.xlsx', 'D.xlsx', 'E.xlsx']
for file in files:
with xw.App(visible=False) as app:
wb = xw.Book('exported_data/' + file)
for sheet in range(len(wb.sheets)):
ws = wb.sheets[sheet]
ws.autofit()
wb.save()
wb.close()