Append images to excel file - python

I have a requirement where i want to append images to my excel sheet.
code to add 1 image:
import pandas as pd
## Create a Pandas dataframe from some data.
df = pd.DataFrame({'Data': [10, 20, 30, 20, 15, 30, 45]})
##Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('pandas_image.xlsx', engine='xlsxwriter')
## Convert the dataframe to an XlsxWriter Excel object.
df.to_excel(writer, sheet_name='Sheet1')
## Get the xlsxwriter workbook and worksheet objects.
workbook = writer.book
worksheet = writer.sheets['Sheet1']
## Insert an image.
worksheet.insert_image('D3', 'newImage.jpg')
## Close the Pandas Excel writer and output the Excel file.
writer.save()
#When I add 1 image to excel
**My requirement :**when I add new photos, it should get appended to my current data.
It should look like

Related

How to write a Dataframe and images to separate worksheets of an excel file

I have found a similar and well answered question, Python: Writing Images and dataframes to the same excel file, but the answer writes the image into the same sheet as the Dataframe. I have 5 images I want to write to separate worksheet to that of the Dataframe.
As this answer is well written I shall use it here if that is ok and ask how to write any 2 images to a separate worksheet in the created workbook?
Code
import pandas as pd
# Create a Pandas dataframe from some data.
df = pd.DataFrame({'Data': [10, 20, 30, 20, 15, 30, 45]})
# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('pandas_image2.xlsx', engine='xlsxwriter')
# Convert the dataframe to an XlsxWriter Excel object.
df.to_excel(writer, sheet_name='Sheet1')
# Get the xlsxwriter workbook and worksheet objects.
workbook = writer.book
worksheet = writer.sheets['Sheet2']
# Insert an image.
worksheet.insert_image('D3', 'TRAJ_FIG.PNG')
# Close the Pandas Excel writer and output the Excel file.
writer.save()
Desired result
An excel workbook with two sheets, the df written to one and 2 images written to the other worksheet.
Instead of using writer, add a new sheet using workbook.add_worksheet():
with pd.ExcelWriter('pandas_image2.xlsx', engine='xlsxwriter') as writer:
df.to_excel(writer, sheet_name='Sheet1')
workbook = writer.book
worksheet = workbook.add_worksheet('Sheet2')
worksheet.insert_image('D3', 'TRAJ_FIG.PNG')

how to append dataframe in existing sheet of excel file using python

You can find what I've tried so far below:
import pandas
from openpyxl import load_workbook
book = load_workbook('C:/Users/Abhijeet/Downloads/New Project/Masterfil.xlsx')
writer = pandas.ExcelWriter('C:/Users/Abhijeet/Downloads/New Project/Masterfiles.xlsx', engine='openpyxl',mode='a',if_sheet_exists='replace')
df.to_excel(writer,'b2b')
writer.save()
writer.close()
Generate Sample data
import pandas as pd
# dataframe Name and Age columns
df = pd.DataFrame({'Col1': ['A', 'B', 'C', 'D'],
'Col2': [10, 0, 30, 50]})
# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('sample.xlsx', engine='xlsxwriter')
# Convert the dataframe to an XlsxWriter Excel object.
df.to_excel(writer, sheet_name='Sheet1', index=False)
# Close the Pandas Excel writer and output the Excel file.
writer.save()
This code will add two columns, Col1 and Col2, with data to Sheet1 of sample.xlsx.
To Append data to existing excel
import pandas as pd
from openpyxl import load_workbook
# new dataframe with same columns
df = pd.DataFrame({'Col1': ['E','F','G','H'],
'Col2': [100,70,40,60]})
writer = pd.ExcelWriter('sample.xlsx', engine='openpyxl')
# try to open an existing workbook
writer.book = load_workbook('sample.xlsx')
# copy existing sheets
writer.sheets = dict((ws.title, ws) for ws in writer.book.worksheets)
# read existing file
reader = pd.read_excel(r'sample.xlsx')
# write out the new sheet
df.to_excel(writer,index=False,header=False,startrow=len(reader)+1)
writer.close()
This code will append data at the end of an excel.
Check these as well
how to append data using openpyxl python to excel file from a specified row?
Suppose you have excel file abc.xlsx.
and You Have Dataframe to be appended as "df1"
1.Read File using Pandas
import pandas as pd
df = pd.read_csv("abc.xlsx")
2.Concat Two dataframes and write to 'abc.xlsx'
finaldf = pd.concat(df,df1)
# write finaldf to abc.xlsx and you are done

How to copy and paste text file into a specified Excel TAB using Python?

I have 5 excel tabs in a certain sheet that I need to copy and paste text files into. I know how to a certain cell of a normal excel sheet with one tab. But I have no idea how to copy and paste each text file to the correct tab as there are formulas in each one.
Any ideas?
you can achive using python panda
import pandas as pd
# Create some Pandas dataframes from some data.
df1 = pd.DataFrame({'Data': [11, 12, 13, 14]})
df2 = pd.DataFrame({'Data': [21, 22, 23, 24]})
df3 = pd.DataFrame({'Data': [31, 32, 33, 34]})
# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('pandas_multiple.xlsx', engine='xlsxwriter')
# Write each dataframe to a different worksheet.
df1.to_excel(writer, sheet_name='Sheet1')
df2.to_excel(writer, sheet_name='Sheet2')
df3.to_excel(writer, sheet_name='Sheet3')
# Close the Pandas Excel writer and output the Excel file.
writer.save()

Problem with different indexing in pandas and xlsxwriter

Here is the code which works fine:
import pandas as pd
# Create a Pandas dataframe from some data.
df = pd.DataFrame({'Data': [10, 20, 30, 20, 15, 30, 45]})
# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('pandas_conditional.xlsx', engine='xlsxwriter')
# Convert the dataframe to an XlsxWriter Excel object.
df.to_excel(writer, sheet_name='Sheet1')
# Get the xlsxwriter workbook and worksheet objects.
workbook = writer.book
worksheet = writer.sheets['Sheet1']
# Apply a conditional format to the cell range.
worksheet.conditional_format(1,1,1,1, {'type': '3_color_scale'}) ##CHANGES THE COLOR OF SECOND ROW
# Close the Pandas Excel writer and output the Excel file.
writer.save()
This creates below output.
My question is, Is it possible to include the Header Data in the pandas indexing? I want to start indexing from 1st row. So Header Data should have index 0. It is useful because in xlsxwriter 1st row has index 0.
Firstly index is an object and default index starts from 0. You can swift it by typing:
df.index += 1
As for the header's index name pandas method to_excel takes an argument which is called index_label. So your code should be:
import pandas as pd
# Create a Pandas dataframe from some data.
df = pd.DataFrame({'Data': [10, 20, 30, 20, 15, 30, 45]})
df.index += 1
# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('pandas_conditional.xlsx', engine='xlsxwriter')
# Convert the dataframe to an XlsxWriter Excel object.
df.to_excel(writer, sheet_name='Sheet1', index_label='0')
# Get the xlsxwriter workbook and worksheet objects.
workbook = writer.book
worksheet = writer.sheets['Sheet1']
# Apply a conditional format to the cell range.
worksheet.conditional_format(1,1,1,1, {'type': '3_color_scale'}) ##CHANGES THE COLOR OF SECOND ROW
# Close the Pandas Excel writer and output the Excel file.
writer.save()
Output:

keeping the same file format when saving .xlsx file using python

Im working on a project where I have to take excel file make changes to the data and save it
from pandas import ExcelWriter
import pandas as pd
dfs = pd.read_excel("infile.xlsx")
#manuplate data
writer = ExcelWriter('outfile.xlsx')
dfs.to_excel(writer,'Sheet5')
writer.save()
The problem I have is the newly saved excel file does not have the same format(cell widht, bold borders) as the input file. What can I do to solve this issue?
You can't preserve the formatting because pandas throws away all that information upon import. You would need to specify the formatting options you want in the output with the ExcelWriter object. If you use the option engine='xlsxwriter' you can then use all the xlsxwriter formatting options before writing the final file. You can find more details in the XlsxWriter documentation.
Example:
import pandas as pd
# This removes the default header style so we can override it later
import pandas.io.formats.excel
pandas.io.formats.excel.header_style = None
# Create a Pandas dataframe from some data.
df = pd.DataFrame({'Data1': [10, 20, 30, 20, 15, 30, 45],
'Data2': [90, 80, 30, 15, 88, 34, 41]})
# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('pandas_conditional.xlsx', engine='xlsxwriter')
# Convert the dataframe to an XlsxWriter Excel object.
df.to_excel(writer, sheet_name='Sheet1')
# Get the xlsxwriter workbook and worksheet objects.
workbook = writer.book
worksheet = writer.sheets['Sheet1']
# Create Format objects to apply to sheet
# https://xlsxwriter.readthedocs.io/format.html#format-methods-and-format-properties
red_bold = workbook.add_format({'bold': True, 'font_color': 'red'})
border = workbook.add_format({'border':5, 'border_color':'blue'})
#Apply formatting to sheet
worksheet.set_column('C:C', None, red_bold)
worksheet.set_column('A1:A8', None, border)
# Apply a conditional format to a cell range.
worksheet.conditional_format('B2:B8', {'type': '3_color_scale'})
# Close the Pandas Excel writer and output the Excel file.
writer.save()

Categories

Resources