title: Exporting a matplotlib chart directly to Excel? Without saving to file first
body: <p>I am trying to write a matplotlib image directly into an Excel file using xlsx writer - ideally without saving the file to the disk.</p>
  
  <p>I have found this answer: <a href="https://stackoverflow.com/questions/30716911/writing-pandas-matplotlib-image-directly-into-xlsx-file">Writing pandas/matplotlib image directly into XLSX file</a> but I cannot get it to work, especially not with Python 3.</p>
  
  <p>This: <code>wks1.insert_image(2,2, imgdata</code> doesn't work, because:</p>
  
  <blockquote>
    <p>path should be string, bytes, os.PathLike or integer, not _io.BytesIO</p>
  </blockquote>
  
  <p>This: <code>wks1.insert_image(2,2,"",{'image data': imgdata}</code>)
  gives a warning</p>
  
  <blockquote>
    <p>Image file '' not found.</p>
  </blockquote>
  
  <p>and produces an excel file with no chart.</p>
  
  <p>What does work is saving the file locally - but I'd like to understand if there's a way to avoid it.</p>
  
  <pre><code>fig.savefig('test.png', format='png')
  wks1.insert_image(2,2, 'test.png')
  </code></pre>
  
  <p>Thoughts? The full code is:</p>
  
  <pre><code>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()
  </code></pre>