pythonexcelpdfcomtypes

Auto size the cells of an excel file in order to print to pdf with comtypes and python


I would like to auto-size the cells and print the result in pdf.The file excel has a single sheet but the name is not costant. This is what I was able to produce by looking online, can anyone help me?

import os
import comtypes.client

SOURCE_DIR = './'
TARGET_DIR = './'

app = comtypes.client.CreateObject('Excel.Application')
app.Visible = False
app.DisplayAlerts = False

infile = os.path.join(os.path.abspath(SOURCE_DIR), 'test.xlsx')
outfile = os.path.join(os.path.abspath(TARGET_DIR), 'test.pdf')

doc = app.Workbooks.Open(infile)

worksheet=doc.Sheets[1]
worksheet.PageSetup.Orientation=2

doc.ExportAsFixedFormat(0, outfile, 1, 0)
doc.Close()

app.Quit()

This convert the file in pdf but I still have to add the auto-size but I am not able to...

P.S. It is quite slow maybe due to the fact that I save the doc but I do changes on the worksheet?

ty for your time


Solution

  • Was easier than I thought I just added:

    worksheet.Columns.AutoFit()