Rotate an image in a Workbook using openpyxl module in python - python

Is there a way to rotate an image inserted into a Workbook created with openpyxl in Python? I can change the width and height of the image but there is no rotate attribute for the image. I can definitely import the image using PIL and rotate it but that snippet code could not be used with the Workbook.
from openpyxl import Workbook
from openpyxl.drawing.image import Image
wb = Workbook()
ws = wb.active
img = Image(r'C:\your path\Image.jpg,png...etc')
img.width= 150
img.height = 200
ws.add_image(img, "C4")
wb.save('imagecheck.xlsx')

Related

Openpyxl is not saving the excel file, why?

here is my code:
import openpyxl as op
from openpyxl import Workbook
from openpyxl import load_workbook
from openpyxl import worksheet
path = ...
op.load_workbook(path)
wb = Workbook()
ws2 = wb.create_sheet('Sheet2')
wb.save(filename = 'NameOfTheFile.xlsx')
Now everything works, except saving the file, when I add:
print(wb.sheetnames)
it does print out the Sheet2 I just added, but for some reason when I go to the documents where the file is, it does not update it, that sheet is nowhere to be found.

Download WMF from pptx and decode to JPEG

Hello stackoverflow users.
I am trying to download an image from the powerpoint presentation and then to process it(to recognize numbers on it at certain coordinates).
My problem is that I can download an image from pptx data only in .wmf format, and I cannot convert it. I have tried all possible solutions already.
from pptx import Presentation
from pptx.enum.shapes import MSO_SHAPE_TYPE
pptx_path = "name_pptx.pptx"
prs = Presentation(pptx_path)
desired_slide = prs.slides[6 - 1]
for shape in desired_slide.shapes:
if shape.shape_type == MSO_SHAPE_TYPE.PICTURE:
image_file_bytes = shape.image.blob
file_extension = shape.image.ext # at this point format is .wfm
Interesting that in Powerpoint I can select a desired .jpeg extension when saving a file.
It took me few hours to solve my problem, convertation of wmf file to jpg is a bit tricky in Windows. I add the image to temporary excel file, and then download an image from it.
class ExcelHelpers():
#staticmethod
def add_img_to_excel(path_to_wmf):
import xlsxwriter
workbook = xlsxwriter.Workbook('test.xlsx')
worksheet = workbook.add_worksheet()
worksheet.insert_image('A1', path_to_wmf)
workbook.close()
#staticmethod
def get_img_from_excel(long_filename):
filename = os.path.basename(long_filename).split('.')[0]
from PIL import ImageGrab
import win32com.client as win32
excel = win32.gencache.EnsureDispatch('Excel.Application')
path_to_excel = os.path.join(os.getcwd(), 'test.xlsx')
workbook = excel.Workbooks.Open(path_to_excel)
for sheet in workbook.Worksheets:
for i, shape in enumerate(sheet.Shapes):
if shape.Name.startswith('Picture'):
shape.Copy()
image = ImageGrab.grabclipboard()
image.save('{}.jpg'.format(filename), 'jpeg')
workbook.Close()
excel.Quit()
del excel
os.remove(long_filename)
os.remove('test.xlsx')

Error with image Python IO in-memory stream save and use

Currently I am trying to plot my DataFrame data and add to my pptx slide. I used matplotlib + pptx-python to do the work. In the process, I tried to save the plot image to io in-memory stream and use it for pptx slide. The steps are:
import io
from PIL import Image
from pptx import Presentation
from pptx.util import Inches
#1. Run Python-pptx and open presentation
prs = Presentation('Template.pptx')
title_slide_layout = prs.slide_layouts[6]
slide = prs.slides.add_slide(title_slide_layout)
title = slide.shapes.title
title.text = 'FileName'
left = top = Inches(1)
#2. plot the data in matplotlib
fig, ax = plt.subplots()
df.groupby('Name').plot(x='Time',y='Score', ax=ax)
#3. save the plot to io in-memory stream
buf = io.BytesIO()
fig.savefig(buf, format='png')
buf.seek(0)
im = Image.open(buf)
#4. add image to slide
pic = slide.shapes.add_picture(im, left, top)
But I got an error like this:
AttributeError: 'PngImageFile' object has no attribute 'read'
Do you know how to solve this problem? BTW I am using Python 3.6. I tried to update PIL package and use 'png' and 'jpg' formats for my image. All efforts didn't work.
Don't use PIL to open the .png file before giving it to .add_picture():
buf = io.BytesIO()
fig.savefig(buf, format='png')
buf.seek(0)
# ---skip the Image.open() step and feed buf directly to .add_picture()
pic = slide.shapes.add_picture(buf, left, top)
The .add_picture() method is looking for a file-like object containing an image, which is buf in this case. When you called Image.open() with buf you get a PIL image object of some sort, which is not what you need.

Insert image in existing excel sheet by using xlsxwriter

i am trying to add image into the existing excel sheet by using xlsxwriter module
import xlsxwriter
workbook = xlsxwriter.Workbook('C:/Users/Desktop/blank.xlsx')
worksheet = workbook.get_worksheet_by_name('Sheet1')
worksheet.insert_image('B5', 'C:/Users/Desktop/CaseDeatails/Abc.jpg')
i am getting the below error
Traceback (most recent call last):
File "C:\Users\Desktop\insertImage.py", line 23, in
worksheet.insert_image('B5', 'C:/Users/Desktop/CaseDeatails/Abc.jpg')
AttributeError: 'NoneType' object has no attribute 'insert_image'
Please help me on this error
inseart image in xlsxwriter
import xlsxwriter
import os
workbook = xlsxwriter.Workbook('C:/Users/Desktop/blank.xlsx')
worksheet = workbook.get_worksheet_by_name('Sheet1')
image = os.path.join(settings.BASE_DIR, "C:/Users/Desktop/CaseDeatails/", "Abc.jpg")
worksheet.insert_image('B5', image)
That isn't possible with XlsxWriter since it cannot read or modify an existing file.
Try the OpenPyXL module instead.
Also for some reason python doesn't like the links to be:
C:/Users/Desktop/blank.xlsx
They have to have a double /, so it should be:
C://Users//Desktop//blank.xlsx
It is not a xlsxwriter solution, but it works well:
from openpyxl import Workbook
from openpyxl.drawing.image import Image
wb = Workbook()
sheet1 = wb.create_sheet('sheet1',0)
active = wb['sheet1']
active.add_image(Image('fig.png'),'A1')
wb.save('myfile.xlsx')

Python parsing XLS with images [duplicate]

I found some Python2 code to extract images from Excel files.
I have a very fundamental question: Where shall I specify the path of my target excel file?
Or does it only work with an active opened Excel file?
import win32com.client # Need pywin32 from pip
from PIL import ImageGrab # Need PIL as well
import os
excel = win32com.client.Dispatch("Excel.Application")
workbook = excel.ActiveWorkbook
wb_folder = workbook.Path
wb_name = workbook.Name
wb_path = os.path.join(wb_folder, wb_name)
#print "Extracting images from %s" % wb_path
print("Extracting images from", wb_path)
image_no = 0
for sheet in workbook.Worksheets:
for n, shape in enumerate(sheet.Shapes):
if shape.Name.startswith("Picture"):
# Some debug output for console
image_no += 1
print("---- Image No. %07i ----", image_no)
# Sequence number the pictures, if there's more than one
num = "" if n == 0 else "_%03i" % n
filename = sheet.Name + num + ".jpg"
file_path = os.path.join (wb_folder, filename)
#print "Saving as %s" % file_path # Debug output
print('Saving as ', file_path)
shape.Copy() # Copies from Excel to Windows clipboard
# Use PIL (python imaging library) to save from Windows clipboard
# to a file
image = ImageGrab.grabclipboard()
image.save(file_path,'jpeg')
You can grab images from existing Excel file like this:
from PIL import ImageGrab
import win32com.client as win32
excel = win32.gencache.EnsureDispatch('Excel.Application')
workbook = excel.Workbooks.Open(r'C:\Users\file.xlsx')
for sheet in workbook.Worksheets:
for i, shape in enumerate(sheet.Shapes):
if shape.Name.startswith('Picture'): # or try 'Image'
shape.Copy()
image = ImageGrab.grabclipboard()
image.save('{}.jpg'.format(i+1), 'jpeg')
An xlsx file is actually a zip file. You can directly get the images from the xl/media subfolder. You can do this in python using the ZipFile class. You don't need to have MS Excel or even run in Windows!
Filepath and filename is defined in the variables here:
wb_folder = workbook.Path
wb_name = workbook.Name
wb_path = os.path.join(wb_folder, wb_name)
In this particular case, it calls the active workbook at the line prior:
workbook = excel.ActiveWorkbook
But you should theoretically be able to specify path using the wb_folder and wb_name variables, as long as you load the file on the excel module (Python: Open Excel Workbook using Win32 COM Api).

Categories