openpyxl - adjust column width size

匿名 (未验证) 提交于 2019-12-03 02:16:02

问题:

I have following script which is converting a CSV file to an XLSX file, but my column size is very narrow. Each time I have to drag them with mouse to read data. Does anybody know how to set column width in openpyxl?

Here is the code I am using.

#!/usr/bin/python2.6 import csv from openpyxl import Workbook from openpyxl.cell import get_column_letter  f = open('users_info_cvs.txt', "rU")  csv.register_dialect('colons', delimiter=':')  reader = csv.reader(f, dialect='colons')  wb = Workbook() dest_filename = r"account_info.xlsx"  ws = wb.worksheets[0] ws.title = "Users Account Information"  for row_index, row in enumerate(reader):     for column_index, cell in enumerate(row):         column_letter = get_column_letter((column_index + 1))         ws.cell('%s%s'%(column_letter, (row_index + 1))).value = cell  wb.save(filename = dest_filename) 

回答1:

You could estimate (or use a mono width font) to achieve this. Let's assume data is a nested array like [['a1','a2'],['b1','b2']]

We can get the max characters in each column. The set the width to that. Width is exactly the width of a monospace font (well not changing other styles at least). Even if you use a variable width font it is a decent estimation. This will not work with formulas.

column_widths = [] for row in data:     for i, cell in enumerate(row):         if len(column_widths) > i:             if len(cell) > column_widths[i]:                 column_widths[i] = len(cell)         else:             column_widths += [len(cell)]  for i, column_width in enumerate(column_widths):     worksheet.column_dimensions[get_column_letter(i+1)].width = column_width 

A bit of a hack but your reports will be more readable.



回答2:

My variation of Bufke's answer. Avoids a bit of branching with the array and ignores empty cells / columns.

ws = your current worksheet dims = {} for row in ws.rows:     for cell in row:         if cell.value:             dims[cell.column] = max((dims.get(cell.column, 0), len(cell.value))) for col, value in dims.items():     ws.column_dimensions[col].width = value 


回答3:

Even more pythonic way to set the width of all columns that works at least in openpyxl version 2.4.0:

for column_cells in worksheet.columns:     length = max(len(as_text(cell.value)) for cell in column_cells)     worksheet.column_dimensions[column_cells[0].column].width = length 

The as_text function should be something that converts the value to a proper length string, like for Python 3:

def as_text(value):     if value is None:         return ""     return str(value) 


回答4:

A slight improvement of the above accepted answer, that I think is more pythonic (asking for forgiveness is better than asking for permission)

column_widths = [] for row in workSheet.iter_rows():     for i, cell in enumerate(row):         try:             column_widths[i] = max(column_widths[i], len(cell.value))         except IndexError:             column_widths.append(len(cell.value))  for i, column_width in enumerate(column_widths):     workSheet.column_dimensions[get_column_letter(i + 1)].width = column_width 


回答5:

I have a problem with merged_cells and autosize not work correctly, if you have the same problem, you can solve with the next code:

for col in worksheet.columns:     max_length = 0     column = col[0].column # Get the column name     for cell in col:         if cell.coordinate in worksheet.merged_cells: # not check merge_cells             continue         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.2     worksheet.column_dimensions[column].width = adjusted_width 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!