Insert image in openpyxl - python

Is it possible to insert an image (jpeg, png, etc) using openpyxl?
Basically I want to place a generated image with a chart below it.
I don't see anything in the documentation, which seems to be a little lacking compared to the maturity of the code.

The following inserts an image in cell A1. Adjust the image location to your needs or handle the creation of the PIL image yourself and hand that to Image()
import openpyxl
wb = openpyxl.Workbook()
ws = wb.worksheets[0]
img = openpyxl.drawing.image.Image('test.jpg')
img.anchor = 'A1'
ws.add_image(img)
wb.save('out.xlsx')
In older versions of openpyxl the following works:
import openpyxl
wb = openpyxl.Workbook()
ws = wb.worksheets[0]
img = openpyxl.drawing.Image('test.jpg')
img.anchor(ws.cell('A1'))
ws.add_image(img)
wb.save('out.xlsx')

Providing a full update on how to do this. This solution uses openpyxl version 2.4.5.
I downloaded an image to my local directory, opened an existing workbook and saved with the image inserted.
import openpyxl
from openpyxl import load_workbook
from openpyxl import Workbook
from openpyxl.drawing.image import Image
from openpyxl.utils import coordinate_from_string
openpyxl_version = openpyxl.__version__
print(openpyxl_version) #to see what version I'm running
# downloaded a .png to local directory manually from
# "https://www.python.org/static/opengraph-icon-200x200.png"
#change to the location and name of your image
png_loc = r'c:\users\me\opengraph-icon-200x200.png'
# test.xlsx already exists in my current directory
wb = load_workbook('test.xlsx')
ws = wb.active
my_png = openpyxl.drawing.image.Image(png_loc)
ws.add_image(my_png, 'B3')
wb.save('test.xlsx')
Results:

This code worked for me:
import openpyxl
wb = openpyxl.Workbook()
ws = wb.worksheets[0]
ws.merge_cells('A1:A3')
img = openpyxl.drawing.image.Image('image.jpg')
row_number = 1
col_idx = 1
cell = ws.cell(row=row_number, column=col_idx)
ws.add_image(img)
wb.save('output.xlsx')

Just to add, I have been using openpyxl==2.5.6 (with Python3.65), and I had to use img.anchor('A1') instead of img.anchor(ws.cell('A1')).
import openpyxl
wb = openpyxl.Workbook()
ws = wb.worksheets[0]
img = openpyxl.drawing.Image('test.jpg')
img.anchor('A1')
ws.add_image(img)
wb.save('out.xlsx')

Related

openpyxl error "There is no item named '[Content_Types].xml' in the archive" [duplicate]

This question already has an answer here:
openpyxl problem Keyerror Content_Types.xml
(1 answer)
Closed last year.
I have a problem with openpyxl, when I want to start the script I get this error, until yesterday it worked and now no more, I tried to uninstall the module, but the problem persists, the excel files I deleted it and nowhere is it open. any ideas?
import openpyxl
from openpyxl import Workbook
from openpyxl import load_workbook
from openpyxl.styles import Border, Side, PatternFill, Font, GradientFill, Alignment
from openpyxl.styles import colors
from openpyxl.cell import Cell
from termcolor import colored, cprint
from openpyxl.styles import numbers
from os import mkdir
myPath = '.\Erstellte Datein' # initialize the Chrome driver
def excel():
# Writing on a EXCEL FILE
filename = (f"{myPath}/Monatsplan openpytesst.xlsx")
dienstorinfo = 'texttest'
emptycell = ' '
x = len(dienstorinfo)
if x == 0:
dienstorinfo = tagesinfo2
try:
wb = load_workbook(filename)
ws = wb.worksheets[0] # select first worksheet
except FileNotFoundError:
headers_row = ['Datum','Dienst','Funktion','Von','Bis','Schichtdauer','Bezahlte Zeit','Überzeit','Sonnats Zulage','Nachtdienst']
wb = Workbook()
ws = wb.active
wb.save(filename)
ws.append(['1','2','2','4','5'])
wb.close()
for cols in ws.iter_cols( ):
if cols[-1].value:
cols[-1].border = Border(left=Side(style='thin'),right=Side(style='thin'),top=Side(style='thin'),bottom=Side(style='thin'))
ws.column_dimensions['A'].width = 11
ws.row_dimensions['1'].height = 25
ws.column_dimensions['B'].width = 60
ws.column_dimensions['C'].width = 2
ws.column_dimensions['D'].width = 3
ws.column_dimensions['E'].width = 3
ws.column_dimensions['F'].width = 3
ws.column_dimensions['H'].width = 3
ws.column_dimensions['I'].width = 2
ws.column_dimensions['L'].width = 2
wb.save(filename)
wb.close()
excel()
It's either your .xlsx file is corrupt or you are referencing the wrong file.
Get a new .xlsx file or look for the file that is not corrupt and start working, this worked for me.

Image not displayed in excell cell (python and openpyxl)

i am tring to create a script using python and openpyxl`s function called add_image which will add resized photos into cells, for this i am using the
following code:
from PIL import Image
from openpyxl import load_workbook
from openpyxl import Workbook
wb = load_workbook('file.xlsx')
ws = wb.active
max_row = ws.max_row
########## SET DIMENSIONS FOR 'F' cells#######
ws.column_dimensions['F'].width=200
for x in range (2,max_row+1):
ws.row_dimensions[x].height=200
##############################################
img = Image.open(file)
bound_width_height = (195, 150)
img.thumbnail(bound_width_height, Image.ANTIALIAS)
nimg = openpyxl.drawing.image.Image(img)
ws.add_image(nimg,'F3')
wb.save('test.xlsx')
print('done!')
but when i am watching into test.xlsx file i see This image cannot curently be displayed.
Result:
https://imgur.com/a/mjgL4hn
Any ideeas why?

Data validation using openpyxl isnt writing to file - code enclosed

The code to actually write each file runs great. The problem I'm having is that the data validation piece doesn't appear to be doing anything. No drop downs are being created in the range I'm referencing.
Thanks in advance for any and all assistance!
%%time
import pandas as pd
import xlsxwriter as ew
import csv as csv
import os
import glob
import openpyxl
#remove existing files from directory
files = glob.glob(#filename)
for f in files:
os.remove(f)
pendpath = #filename
df = pd.read_sas(pendpath)
allusers = df.UserID_NB.unique()
listuserpath = #filename
listusers = pd.read_csv(listuserpath)
listusers = listusers['USER_ID'].apply(lambda x: str(x).strip())
for id in listusers:
x = df.loc[df['UserID_NB']==id]
path = #filename
x.to_excel(path, sheet_name = str(id), index = False)
from openpyxl import load_workbook
wb = openpyxl.load_workbook(filename = path)
sheet = wb.get_sheet_by_name(str(id))
maxrow = sheet.max_row
from openpyxl.worksheet.datavalidation import DataValidation
dv = DataValidation(type="list", formula1='"Yes,No"', allow_blank=False, showDropDown = True)
rangevar = 'R1:T'+ str(maxrow)
dv.ranges.append(rangevar)
wb.save(path)
print str(id), rangevar
Code for Basic Sheet
import openpyxl
wb = openpyxl.Workbook()
ws = wb.active
sheet.title = 'testsheet'
path = '#filepath'
from openpyxl.worksheet.datavalidation import DataValidation
dv = DataValidation(type="list", formula1='"Yes,No"', allow_blank=False, showDropDown = True)
dv.ranges.append('A1')
wb.save(path)
You are missing to add the dv to the worksheet.
>>> # Add the data-validation object to the worksheet
>>> ws.add_data_validation(dv)
Read the docs about validation

append rows in Excel using XLWT in Python

How to find total number of rows using XLWT or XLRD in Python? I have an excel file(accounts.xls) and would like to append rows in it.
I am getting an error here - AttributeError: 'Sheet' object has no attribute 'write'
from xlrd import open_workbook
from xlwt import Workbook
def saveWorkSpace(fields,r):
wb = open_workbook('accounts.xls')
ws = wb.sheet_by_index(0)
r = ws.nrows
r += 1
wb = Workbook()
ws.write(r,0,fields['name'])
ws.write(r,1,fields['phone'])
ws.write(r,2,fields['email'])
wb.save('accounts.xls')
print 'Wrote accounts.xls'
Here is the solution of the above question
import xlrd
import xlwt
from xlutils.copy import copy
def saveWorkSpace(fields):
rb = xlrd.open_workbook('accounts.xls',formatting_info=True)
r_sheet = rb.sheet_by_index(0)
r = r_sheet.nrows
wb = copy(rb)
sheet = wb.get_sheet(0)
sheet.write(r,0,fields['name'])
sheet.write(r,1,fields['phone'])
sheet.write(r,2,fields['email'])
wb.save('accounts.xls')
print 'Wrote accounts.xls'
Python Program to add Values to the last data row an Excel sheet.
from xlwt import Workbook
from xlrd import open_workbook
import openpyxl
# Function to get the last RowCount in the Excel sheet , change the index of the sheet accordingly to get desired sheet.
def getDataColumn():
#define the variables
rowCount=0
columnNumber=0
wb = open_workbook('C:\\Temp\\exp\\data.xlsx')
ws = wb.sheet_by_index(0)
rowCount = ws.nrows
rowCount+=1
columnNumber=1
print(rowCount)
writedata(rowCount,columnNumber)
#Data to specified cells.
def writedata(rowNumber,columnNumber):
book = openpyxl.load_workbook('C:\\Temp\\exp\\data.xlsx')
sheet = book.get_sheet_by_name('Sheet1')
sheet.cell(row=rowNumber, column=columnNumber).value = 'Appended Data'
book.save('C:\\Temp\\exp\\data.xlsx')
print('saved')
getDataColumn()
exit()

openpyxl create a function that references a cell in another sheet

I just started working with openpyxl a couple of days ago and its a great library. However, the documentation seems to be sparse for advanced features. I have a couple of issues.
openpyxl seems to change the formula that I insert to a lower case which results in an unknown reference from excel.
furthermore, i changed the name of the sheet to accomidate the lowercase and still found a #NAME? error in the cell where the reference was at.
Can someone please show me how or where to find out how to reference a cell from another sheet in openpyxl
import openpyxl.Workbook
wb = Workbook()
ws = wb.get_active_sheet()
#shows up lowercase with name error in excel
ws.cell('A1).value = "$'Sheet'.E7 + 123"
#still shows a name error in excel
ws.cell('A2').value = "$'sheet'.E7 + 123"
Try this:
from openpyxl import Workbook
wb = Workbook()
ws = wb.create_sheet()
ws.title ='NewSheet'
ws.cell('E7').value = 7
ws = wb.create_sheet()
ws.cell('A1').value = "=NewSheet!E7 + 123"
wb.save( filename = 'temp2.xlsx' )
from openpyxl import Workbook, utils
wb = Workbook()
ws = wb.create_sheet()
ws.title ='NewSheet'
ws.cell('E7').value = 7
ws = wb.create_sheet()
ws.cell('A1').value = f"={utils.quote_sheetname(ws.title)}!E7 + 123"
wb.save( filename = 'temp2.xlsx' )
The problem with the previous answer is that it's dependant on the title of the sheet being 'NewSheet'. Using quote_sheetname()controls that.

Categories

Resources