J-Eubanks J-Eubanks - 1 year ago 39
Python Question

Exporting plain text header and image to Excel

I am fairly new to Python, but I'm getting stuck trying to pass an image file into a header during the

portion of my file.

Basically what I want is a picture in the first cell of the Excel table, followed by a couple of rows (5 to be exact) of text which will include a date (probably from
if possible).

I already have the code to output the table portion as:

mydataframe.to_excel(my_path_name, sheet_name= my_sheet_name, index=False, startrow=7,startcol=0)

Is there a way to output the image and text portion directly from Python?


For clarity,
is exporting the meat and potatoes of the worksheet (data rows and columns). I already have it starting on row 7 of the worksheet in Excel. The header portion is the trouble spot.

Answer Source

I found the solution and thanks for all of the help.

The simple answer is to use the xlsxwriter package as the engine. In other words assume that the image is saved at the path /image.png. Then the code to insert the data into the excel file with the image located at the top of the data would be:

# Importing packages and storing string for image file
import pandas as pd
import xlsxwriter
import numpy as np
image_file = '/image.png'

# Creating a fictitious data set since the actual data doesn't matter
dataframe = pd.DataFrame(np.random.rand(5,2),columns=['a','b'])

# Opening the xlsxwriter object to a path on the C:/ drive
writer = pd.ExcelWriter('C:/file.xlsx',engine='xlsxwriter')

dataframe.to_excel(writer,sheet_name = 'Arbitrary', startrow=3)

# Accessing the workbook / worksheet
workbook = writer.book
worksheet = writer.sheets['Arbitrary']

# Inserting the image into the workbook in cell A1

# Closing the workbook and saving the file to the specified path and filename

And now I have an image on the top of my excel file. Huzzah!