Insert image in existing excel sheet by using xlsxwriter
Asked Answered
L

5

5

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

Lasandralasater answered 2/11, 2016 at 6:26 Comment(0)
G
4

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)
Gravitation answered 17/12, 2020 at 8:17 Comment(1)
I have got following error: "NameError: name 'settings' is not defined". Could somebody help?Discriminatory
U
3

That isn't possible with XlsxWriter since it cannot read or modify an existing file.

Try the OpenPyXL module instead.

Unchaste answered 2/11, 2016 at 8:48 Comment(0)
D
1

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')
Discriminatory answered 10/12, 2021 at 22:17 Comment(0)
M
0

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
Miscellany answered 13/11, 2020 at 20:54 Comment(0)
P
0

I found a solution that works for me. I've used it in a loop to insert multiple images into multiple sheets.

from openpyxl import load_workbook
from openpyxl.drawing.image import Image

sheets = [0,1,2]
img_list = ['Existing_img.png','Existing_img1.png','Existing_img2.png']

new_excel_file = "some_existing_file.xlsx"
wb = load_workbook(new_excel_file)

for sheet, image in zip(sheets, img_list):
    ws = wb.worksheets[sheet]
    img = Image(image)
    ws.add_image(img, "J2")
    wb.save(new_excel_file)

Here is the code for inserting a single image into an existing sheet:

new_excel_file = "some_existing_file.xlsx"
wb = load_workbook(new_excel_file)
ws = wb.worksheets[0]
img = Image("some_existing_image.png")

ws.add_image(img, "J2")

wb.save(new_excel_file)
Piping answered 17/5, 2023 at 23:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.