I am trying to write a matplotlib image directly into an Excel file using xlsx writer - ideally without saving the file to the disk.
I have found this answer: Writing pandas/matplotlib image directly into XLSX file but I cannot get it to work, especially not with Python 3.
This: wks1.insert_image(2,2, imgdata
doesn't work, because:
path should be string, bytes, os.PathLike or integer, not _io.BytesIO
This: wks1.insert_image(2,2,"",{'image data': imgdata}
)
gives a warning
Image file '' not found.
and produces an excel file with no chart.
What does work is saving the file locally - but I'd like to understand if there's a way to avoid it.
fig.savefig('test.png', format='png')
wks1.insert_image(2,2, 'test.png')
Thoughts? The full code is:
import xlsxwriter
import numpy as np
import matplotlib.pyplot as plt
import io
x=np.linspace(-10,10,100)
y=x**2
fig,ax=plt.subplots()
ax.plot(x,y)
workbook = xlsxwriter.Workbook('test chart.xlsx')
wks1=workbook.add_worksheet('Test chart')
wks1.write(0,0,'test')
imgdata=io.BytesIO()
fig.savefig(imgdata, format='png')
wks1.insert_image(2,2,"",{'image data': imgdata})
#wks1.insert_image(2,2, imgdata)
workbook.close()
According to the documentation (and the link to the question you provided), the correct spelling for the optional argument to be passed to insert_image
is image_data
(noting the underscore _)
import xlsxwriter
import numpy as np
import matplotlib.pyplot as plt
import io
x=np.linspace(-10,10,100)
y=x**2
fig,ax=plt.subplots()
ax.plot(x,y)
workbook = xlsxwriter.Workbook('test chart.xlsx')
wks1=workbook.add_worksheet('Test chart')
wks1.write(0,0,'test')
imgdata=io.BytesIO()
fig.savefig(imgdata, format='png')
wks1.insert_image(2,2, '', {'image_data': imgdata})
workbook.close()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With