简体   繁体   中英

How to get a range of cells while retaining their format from an .xlsx document?

I am trying to print a range of cells from xlsx to pdf using below code

from win32com import client

xlApp = client.Dispatch("Excel.Application")
books = xlApp.Workbooks.Open('C:\\Users\....\\2020.xlsx')
ws = books.Worksheets['TEST']
ws.Visible = 1
ws.ExportAsFixedFormat(0, 'C:\\Users\.....\\trial.pdf')

This code works fine. However, I would like to tweak to print only the cells ranging from A1 to K50 ; and should retain the cell formatting from excel when converted to PDF. Is this possible?

It is very hard to format using python code with other third party packages. Below solution is useful when either the formatting requires a lot of effort or when the formatting may be dynamic & you may need to just print the excel like the way it is:

This solution is done using the below code (note the trick is using IgnorePrintAreas=False ), however, the ranges that I wanted to print I set it up as the printable range on excel. This will print the range that I am interested in & with the format that is present in Excel.

from win32com import client
xlApp = client.Dispatch("Excel.Application")
books = xlApp.Workbooks.Open('C:\\Users\....\\2020.xlsx')
ws = books.Worksheets['TEST']
ws.Visible = 1
ws.ExportAsFixedFormat(0, 'C:\\Users\.....\\trial.pdf',IgnorePrintAreas=False)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM