Skip to content

Instantly share code, notes, and snippets.

@bisco
Created August 7, 2019 13:52
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bisco/a65e71c8ba45337f91174e6ae3c139f9 to your computer and use it in GitHub Desktop.
Save bisco/a65e71c8ba45337f91174e6ae3c139f9 to your computer and use it in GitHub Desktop.
openpyxlで列幅を調整する
# https://stackoverflow.com/questions/39529662/python-automatically-adjust-width-of-an-excel-files-columns
# これのサンプルコードが動かないので直したもの
def adjust_col(ws):
for col in ws.columns:
max_length = 0
column = col[0].column # Get the column name
column = chr(ord("A") - 1 + column)
for cell in col:
try: # Necessary to avoid error on empty cells
if len(str(cell.value)) > max_length:
max_length = len(cell.value)
except:
pass
adjusted_width = (max_length + 2) * 1.1
ws.column_dimensions[column].width = adjusted_width
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment