I'm tired of being able to fill up a lot of image files, so I want to paste them in one Excel file.
Save the figure to a file in image format and paste the image with insert_image of xlsxwriter It seems useless to write it out once, but I think this is the easiest
import matplotlib.pyplot as plt
import numpy as np
#Create sample figure
plt.close(1) #It doesn't have to be, but it's an initial feeling
fig, ax = plt.subplots(1, 1, figsize=(6,3))
ax.barh(y=range(10),width=range(10))
plt.tight_layout()
#Save image
image_file_path = 'tmp.png'
fig.savefig(image_file_path)
#Open a new workbook, create a sheet
import xlsxwriter
workbook = xlsxwriter.Workbook('tmp.xlsx')
worksheet = workbook.add_worksheet()
#Paste the image in the cell
worksheet.insert_image('A1', image_file_path)
worksheet.insert_image('K1', image_file_path, {'x_scale': 0.7, 'y_scale': 0.7})
worksheet.insert_image(19, 0, image_file_path)
worksheet.insert_image(19, 10, image_file_path)
#Zoom adjustment
worksheet.set_zoom(50)
#Close the Excel workbook and finish
workbook.close()
Official documentation for xlsxwriter. It's fairly solid. search is convenient. https://xlsxwriter.readthedocs.io/worksheet.html#insert_image
Recommended Posts