Skip to content

Instantly share code, notes, and snippets.

@garymanley
Created December 28, 2017 11:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save garymanley/6b64e8c65fc6ffd7eadefeb8449cce8b to your computer and use it in GitHub Desktop.
Save garymanley/6b64e8c65fc6ffd7eadefeb8449cce8b to your computer and use it in GitHub Desktop.
Export Graphs from Excel using XLwings
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 28 10:49:01 2017
@author: garym
"""
## Required imports
import xlwings as xw
import glob
import os
import datetime
from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH
## set up folder locations
input_dir = 'C:\\Users\\garym\\Documents\\New folder (2)\\'
output_dir = r'C:\Users\garym\Documents\PyWinAutoBlog\Output'
## set up extracting graphs
Excel = True
if Excel:
## get latest file
list_of_files = glob.glob(input_dir + 'Running*.xlsx')
latest_file = max(list_of_files, key=os.path.getctime)
#xw.App(visible=True)
wb = xw.Book(latest_file)
## loop through graphs and save as a picture
i = 0
for chart in wb.sheets['Dashboard'].api.ChartObjects():
chart.Chart.Export(output_dir+'\\chart' + str(i) + ".png")
i = i+1
## close excel
wb.close()
### Open new document
document = Document()
## add picture and then centre it
document.add_picture(output_dir+r'\chart1.png')
last_paragraph = document.paragraphs[-1]
last_paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
### Add more pictures
document.add_picture(output_dir+r'\chart0.png')
document.add_picture(output_dir+r'\chart2.png')
document.add_picture(output_dir+r'\chart3.png')
## set up filename
filenamedocx = output_dir+r'\Running_report'+datetime.datetime.today().strftime('%d%m%y')+'.docx'
## save document
document.save(filenamedocx)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment