0

I need to get column widths from Excel and write them to a .txt file. I believe openpyxl is the way to do it, but I cannot get the openpyxl.worksheet.dimensions.ColumnDimension.width to return a value. Is this the right approach?

Tibbs
  • 53
  • 1
  • 3

1 Answers1

1
  • Here is an alternate method, which instantiates Excel as an object.
  • This only works on Windows, and if Excel is installed.

Given:

enter image description here

Code:

import win32com.client as win32

filename = 'D:/PythonProjects/stack_overflow/test.xlsx'

excel = win32.gencache.EnsureDispatch('Excel.Application')
excel.Visible = False  # can be True if you like

wb = excel.Workbooks.Open(filename)
ws1 = wb.Sheets('Sheet1')

for x in range(1, ws1.UsedRange.Columns.Count +1):
    print(ws1.Columns(x).ColumnWidth)

wb.Close(True)

Output:

8.43
8.43
8.43
8.43
8.43
39.43
  • ws1.UsedRange.Columns.Count returns an int of the number of used columns, in the Excel screenshot A:F == 1:6
  • ws1.Columns(x).ColumnWidth returns the column width
  • Incidentally, using this method to interact with Excel exposes all Excel functions, allowing for interaction with new or existing files, graphing, formatting, etc.
    • If excel.Visible = True, operations can be performed on the live file while you watch; just don't interact with Excel with python is working on it.
Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158