I need to create an excel file and add images to certain cells so in each row I add two images in A1 and B1. I need to do this for around 150 images by copying and pasting them?
Can someone tell me how to do that using python script automatically by just defining the images path and the excel file path and the number of the images in the folder?
Using the xlsxwriter library
import xlsxwriter
# creates an excel sheet
workbook = xlsxwriter.Workbook('images.xlsx')
worksheet = workbook.add_worksheet()
worksheet.insert_image('B2', 'your-image-name.png')
workbook.close()
See the xlsxwriter docs for more details
Related
i am trying to copy an excel spreadsheet which has some text and numbers and a logo image into multiple excel files as a new sheet with source formatting using python, any help is greatly appreciated.
It's not clear what your end requirement and restrictions are.
The basic requirement;
"I am trying to copy an excel spreadsheet which has some text and numbers and a logo image into multiple excel files"
just indicates you want multiple copies of the same Excel file, the File Management app of your OS can do this, with the limitation perhaps being the resultant naming of each file. If this is your requirement then perhaps something like
Python - making copies of a file
may help to create the files with the necessary naming.
If its a workbook with multiple sheets and you only want one sheet copied to new workbooks then openpyxl can help. Copying sheets is easy enough however the formatting requires extra code.
If there is just a couple of sheets in the original it may be easier to just remove those sheets before saving your copy, see example code below.
Otherwise this link may help
How to copy worksheet from one workbook to another one using openpyxl?
Example:
The following code shows how to open an existing workbook, 'templateA.xlsx' which has two sheets, 'Sheet1 & 'Sheet2'. You only want 'Sheet1' saved as multiple copies (10) named 'template1.xlsx', 'template2.xlsx', 'template3.xlsx'...
The code open the original workook, deletes the sheet called 'Sheet2' before making 10 copies.
from openpyxl import load_workbook
# Load the original Excel workbook
wb = load_workbook("templateA.xlsx")
# delete the Sheet2 that is not required
del wb["Sheet2"]
# Save 10 copies of the workbook with Sheet1 only
for i in range(10):
wb.save("template" + str(i) + ".xlsx")
The first link python-making-copies-of-a-file can help if your required naming is more complex than the example given.
openpyxl
I am trying to add a large dataset to an existing xls spreadsheet.
I'm currently writing to it using a pandas dataframe and the .to_excel() function, however this erases the existing data in the (multi-sheet) workbook. The existing spreadsheet is very large and complex,it also interacts with several other files, so I can't convert it to xlsx or read and rewrite all of the data, as I've seen some suggestions on other questions. I want the data that I am adding to be pasted starting from a set row in an existing sheet.
Yes , you can use the library xlsxwriter , link= https://xlsxwriter.readthedocs.io
code example :
import xlsxwriter
Name="MyFile"+".xlsx"
workbook = xlsxwriter.Workbook(Name)
worksheet = workbook.add_worksheet()
worksheet.write("A1", "Incident category".decode("utf-8"))
worksheet.write("B1", "Longitude".decode("utf-8"))
worksheet.write("C1", "Latitude".decode("utf-8"))
workbook.close()
I want to save excel sheet with existing sheet formats and background color.
I could save successfully to a new file with out old file format.
How can I keep the existing excel sheet format when save in to a new file.
writer = pd.ExcelWriter('New.xlsx', engine='xlsxwriter')
dfDiff.to_excel(writer, sheet_name='DIFF', index=False)
writer.save()
I had no good experience with pandas and format styles... what works if you use win32com like this example:
from win32com.client import DispatchEx
excel = DispatchEx('Excel.Application')
wbP=excel.Workbooks.Open(r'C:\Temp\Junk\Temp.xlsx')
wbG=excel.Workbooks.Open(r'C:\Temp\Junk\Temp2.xlsx')
wbG.Worksheets('TAA2').Copy(Before=wbP.Worksheets("TAA"))
wbP.SaveAs(r'C:\Temp\Junk\Temp.xlsx')
excel.Quit()
del excel # ensure Excel process ends
this copies everything... (styles, formats, formulas etc.)
Another option is copy the whole workbook and delete the not needed sheets, if you create a new file and not editing an existing one...
Copy worksheet from one workbook to another one using Openpyxl
Is there is way to create sheet 2 in same csv file by using python code
yes. There is :
df = pd.read_excel("C:\\DWDM\\Status.xlsx") # read ur original file
workbook = load_workbook(filename="C:\\DWDM\\Status.xlsx")
ws2 = workbook.create_sheet("Summary", 0) # other sheet with name Summary is added to the same.
and you can check the same with "workbook.sheetnames"
You can do this by using multiple CSV files - one CSV file per sheet.
A comma-separated value file is a plain text format. It is only going to be able to represent flat data, such as a table (or a "sheet")
When storing multiple sheets, you should use separate CSV files. You can write each one separately and import/parse them individually into their destination.
I am fairly new to Python, but I'm getting stuck trying to pass an image file into a header during the DataFrame.to_excel() 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 datetime.date.today().ctime() 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?
UPDATE:
For clarity, mydataframe 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.
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
worksheet.insert_image('A1',image_file)
# Closing the workbook and saving the file to the specified path and filename
writer.save()
And now I have an image on the top of my excel file. Huzzah!