Reputation: 611
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
Upvotes: 5
Views: 9862
Reputation: 41524
That isn't possible with XlsxWriter since it cannot read or modify an existing file.
Try the OpenPyXL module instead.
Upvotes: 3
Reputation: 79
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)
Upvotes: 0
Reputation: 341
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')
Upvotes: 1
Reputation: 746
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)
Upvotes: 4
Reputation: 1
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
Upvotes: 0