How get some columns from an excel sheets and save as pdf with client dispatch?

72 views Asked by At

I have an excel file with six columns (Number, Name, Group, folio, adress and e-mail), i need to use client dispatch, to get only the columns (Name, Group and e-mai) of the sheet and save it as pdf in a new folder.

I have the next code.

bas=r'D:\Users\Aplication'

excel= client.Dispatch("Excel.Application")
excel.Visible=False
excel.ScreenUpdating= False
excel.EnableEvents= False
excel.Interactive= False
excel.DisplayAlerts=False

sheets2= excel.Workbooks.Open(os.path.join(os.path.join(bas,"Report"),f"GroupA.xlsx"))
work_sheets2=sheets2.Worksheets[0]
work_sheets2.Range('B:B','C:C','F:F')
work_sheets2.ExportAsFixedFormat(0,os.path.join(os.path.join(bas,"Proofpdf"),f"ListA.pdf"),OpenAfterPublish=0)
sheets2.Close(True)

It work, but the result is a PDF with the samen six columns in the excel file. Can someone help me to select and save in a PDF file only some columns of the excel?

1

There are 1 answers

0
moken On BEST ANSWER

I dont think it works to use non consecutive columns in the range. Certainly I would have expected this line

work_sheets2.Range('B:B','C:C','F:F') 

to return a error. Either way you did not select the range, the line is a statement that is not applied to anything. You need to assign to a variable then export that range, see code sample.

Also would expect this line to return a error for selecting the worksheet.

work_sheets2=sheets2.Worksheets[0]

Anyway you could temporarily copy Column F into the position of Column D so you have a consecutive range, B - D and use that range for the PDF.
Then after the export just delete Column D.

Example Code

import os
from win32com import client


xlToRight = -4161

bas=r'D:\Users\Aplication'

excel = client.Dispatch("Excel.Application")
excel.Visible = False
excel.ScreenUpdating = False
excel.EnableEvents = False
excel.Interactive = False
excel.DisplayAlerts = False

sheets2 = excel.Workbooks.Open(os.path.join(os.path.join(bas, "Report"), f"GroupA.xlsx"))
sheet_names = [sheet.Name for sheet in sheets2.Sheets]

### Select the required sheet
# work_sheets2 = sheets2.Worksheets[0]
work_sheets2 = sheets2.Worksheets(1)

### Insert a copy of Column F into position of column D
work_sheets2.Range("F:F").Copy()
work_sheets2.Range("D:D").Insert(Shift=xlToRight)

### Set range of data to export and assign to variable 'rng'
# work_sheets2.Range('B:B', 'C:C', 'F:F')
rng = work_sheets2.Range('B:B', 'D:D')

### Export 'rng' to PDF
rng.ExportAsFixedFormat(0, os.path.join(os.path.join(bas, "Proofpdf"), f"ListA.pdf"), OpenAfterPublish=0)

### Delete temp copied Column
work_sheets2.Range("D:D").Delete()

### Close and exit
sheets2.Close(True)
excel.Quit()

For the example sheet;
enter image description here

the PDF is
enter image description here