Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

openpyxl - adjust column width size

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) 
like image 386
Satish Avatar asked Nov 02 '12 14:11

Satish


People also ask

How do I change the column width in Openpyxl?

In order to change the column width size, you can make use of the column_dimesnsions method of the worksheet class.

How do I set column width in python?

Setting the Column Width Set the width of a column by calling the Cells collection's setColumnWidth method. The setColumnWidth method takes the following parameters: Column index, the index of the column that you're changing the width of. Column width, the desired column width.

Which is better Openpyxl vs XlsxWriter?

If you are working with large files or are particularly concerned about speed then you may find XlsxWriter a better choice than OpenPyXL. XlsxWriter is a Python module that can be used to write text, numbers, formulas and hyperlinks to multiple worksheets in an Excel 2007+ XLSX file.


1 Answers

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. Then set the width to that. Width is exactly the width of a monospace font (if 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.

from openpyxl.utils import get_column_letter  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,1):  # ,1 to start at 1     worksheet.column_dimensions[get_column_letter(i)].width = column_width 

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

like image 142
Bufke Avatar answered Oct 23 '22 01:10

Bufke