Newbie - I have a Python script that adjusts the width of different columns of an excel file, according to the values specified:
import openpyxl from string import ascii_uppercase newFile = "D:\Excel Files\abc.xlsx" wb = openpyxl.load_workbook(filename = newFile) worksheet = wb.active for column in ascii_uppercase: if (column=='A'): worksheet.column_dimensions[column].width = 30 elif (column=='B'): worksheet.column_dimensions[column].width = 40 elif (column=='G'): worksheet.column_dimensions[column].width = 45 else: worksheet.column_dimensions[column].width = 15 wb.save(newFile)
Is there any way through which we can adjust the width of every column to its most optimum value, without explicitly specifying it for different columns (means, without using this "if-elif-elif-......-elif-else" structure)? Thanks!
The easiest way to auto-size the width and height of a column is to call the Worksheet class' autoFitColumn method. The autoFitColumn method takes the column index (of the column about to be resized) as a parameter. Copy def autofit_column(self): \# Instantiating a Workbook object by excel file path workbook = self.
Change the column width to automatically fit the contents (AutoFit) Select the column or columns that you want to change. On the Home tab, in the Cells group, click Format. Under Cell Size, click AutoFit Column Width.
The with of 1 unit of the xlsxwriter columns is about equal to the width of one character. So, you can simulate autofit by setting each column to the max number of characters in that column.
for col in worksheet.columns: max_length = 0 column = col[0].column_letter # Get the column name for cell in col: try: # Necessary to avoid error on empty cells if len(str(cell.value)) > max_length: max_length = len(str(cell.value)) except: pass adjusted_width = (max_length + 2) * 1.2 worksheet.column_dimensions[column].width = adjusted_width
This could probably be made neater but it does the job. You will want to play around with the adjusted_width value according to what is good for the font you are using when viewing it. If you use a monotype you can get it exact but its not a one-to-one correlation so you will still need to adjust it a bit.
If you want to get fancy and exact without monotype you could sort letters by width and assign each width a float value which you then add up. This would require a third loop parsing each character in the cell value and summing up the result for each column and probably a dictionary sorting characters by width, perhaps overkill but cool if you do it.
Edit: Actually there seems to be a better way of measuring visual size of text: link personally I would prefer the matplotlib technique.
Hope I could be of help, my very first stackoverflow answer =)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With