Why does my header image disappear from my template? - python

I made a template document in Excel which is mostly empty, except for the header which contains the logo of our department (below).
I then read this template document into python using openpyxl and populate it with a data frame. However, when I save the workbook and open the Excel doc, everything is intact except my image disappears.
How can I ensure my logo stays intact in the report? I know I can't insert an image into the header in openpyxl, so I was hoping by including it in my template (and never touching the header) it would stay but it isn't.
Code in Python
from openpyxl import load_workbook
from openpyxl.utils.dataframe import dataframe_to_rows
wb = load_workbook('./template.xlsx')
ws = wb["Sheet1"]
for r in dataframe_to_rows(df, index=False, header=False):
ws.append(r)
wb.save("{}".format(fn))

Unfortunately openpyxl does not support images at this time, see official documentation: https://openpyxl.readthedocs.io/en/stable/usage.html#read-an-existing-workbook
openpyxl does currently not read all possible items in an Excel file
so images and charts will be lost from existing files if they are
opened and saved with the same name.
So when you open the template file, the images are not read, thus not saved in the new file.
Therefore, you may have to switch to using xlsxwriter.

Related

Openpyxl don't preserve formatting

I have an excel file that i want to use as template, what i need is just change the values of some cells, and save it as another excel file. The problem is that when i save it the formatting, style and some date values are changed
from openpyxl import load_workbook
wb = load_workbook("test.xlsx")
ws = wb["RDO"]
ws["B8"].value = "MAI MAN"
wb.save("new.xlsx")
The old file:
The new one:
As you can see the borders and date fields were changed.
I was thinking in just unzip the excel and modify the xml files, then zip it back, but this approach has a problem. I will need to make a copy of some worksheets, so i tought i should be ok in just copy and paste the sheet.xml file and change the workbook.xml file to add this new sheet, but when i do this all the cells are cleared which is weird because when i copy the sheet in the excel program the output sheet file it's exactly the same as the original
I would like some simple solution if possible, maybe some other library or a fix for this xml sheet problem

Excel from Python (openpyxl) Issue

I'm new to programming and I'm trying to make a small app where I'll need to copy and paste values to a "stylished" excel woorksheet but when I was testing the first commands, I ran to the first issue:
When I get a cell value from "worksheet1" and paste it into an empty cell from the same worksheet ("worksheet1"), the worksheet stylish kinda messes up (just border cells disapearing), and thats not good, because that table is going to be printed and I need those border cells to stay.
I made a video with the issue: https://www.youtube.com/watch?v=DCZAwYp4zvE
I've tried:
Changing the files directory
Copying the excel file
Making the same but in the other woorksheets
I downloaded the original excel from internet so I though it was some incompatibility issue. I even created a new workbook and duplicated from 0 the original workbook (borders, same font, font size, etc), but didnt fix it.
Code:
from openpyxl import load_workbook
file="Test.xlsx"
wb = load_workbook(file)
ws = wb["COMPRA_DIRECTA"]
ws["A80"] = ws["A13"].value
wb.save(file)
Link to the original excel and the script: Link
Im using:
Excel 2016
Openpyxl 2.5.14
Windows
I have used the encoding and it is working fine for me. I have installed Openpyxl 2.6.4 and using LibreOffice Calc on Ubuntu 18.04.
Try this code, it will surely work for you:
from openpyxl import load_workbook
file="Test.xlsx"
wb = load_workbook(file)
# grab the active worksheet
ws = wb["COMPRA_DIRECTA"]
# Data can be assigned directly to cells
ws['A80'] = ws["A13"].value.encode("utf8")
# Save the file
wb.save("sample.xlsx")

merged cells are broken after load/save using openpyxl

I am opening a .xlsm file using openpyxl abd updated some cells in it and then saved as .xlsm file.Now when I open the saved file I see that the cells which were merged in the original file are broken in new file.
the code which i am using is-
from openpyxl import Workbook
from openpyxl import load_workbook
wb = load_workbook('Excel.xlsm',read_only=False ,keep_vba=True)
ws = wb['K0 Reg Patch Util']
ws.cell(row=42,column=3).value = 25
ws.cell(row=43,column=3).value = 30
ws.cell(row=44,column=3).value = 24
wb.save('Test.xlsm')
Even on simple opening and saving file with openpyxl merged columns borders in the original file are broken. I have searched many times regarding this problem but none of the solutions were satisfying. I even came across a monkeypatch script which is to be included in the script after including the openpyxl library.The source for the script is-
https://bitbucket.org/openpyxl/openpyxl/issues/365/styling-merged-cells-isnt-working
The monkeypatch will overwrite the definition of merged cell from that present in the library.
can somebody tell me how to include this patch in the script and What does "self" means in the script.
I ran into a similar issue. But for me this only occurs with "protected" excel files. Removing that protection worked for me. No more "broken" merged cells. At least for files with .XLSX extension, I did not test .XLSM.

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 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!

How to preserve macro buttons in Excel when adding data with Python

For a process I am maintaining, I have a script that creates a csv file and then I copy the csv file into an Excel workbook with buttons that activate macros. This process works just fine.
I am trying to improve that process by writing a script that builds the workbook directly, thus eliminating a step. I thought the best way to do that was to create a template workbook where the first worksheet has the macro button. Then I would simply copy the template workbook, add in my data and save the new workbook under a new custom name. My test code is below:
import csv, os, sys, xlrd, xlwt, xlutils, shutil
from copy import deepcopy
from xlutils import save
from xlutils.copy import copy
templatefile = 'N:\Tools\Scripts-DEV\Testing_Template.xls'
Destfile = 'N:\Tools\Scripts-DEV\Testing_Dest.xls'
shutil.copy(templatefile,Destfile)
# Works fine up to here.
# If you look at the new file, it has the button that is in the template file.
rb = xlrd.open_workbook(Destfile)
rs = rb.sheet_by_index(0)
wb = copy(rb)
wb.get_sheet(0).write(3, 0, 'Due Date')
wb.get_sheet(0).write(3, 1, 'Name')
wb.get_sheet(0).write(3, 3, 'Category')
wb.get_sheet(0).write(3, 4, 'Number')
wb.save(Destfile)
Here is where the problem shows up. After you save, the macro button disappears. I've been looking for a couple days but I haven't (yet) found a way to save the updated Excel file without losing the macro button.
I've been looking at Preserving styles using python's xlrd,xlwt, and xlutils.copy but that doesn't quite meet my needs as I'm trying to preserve a button, not a style.
Does anyone know a way to do this?
I'm about to start looking at alternatives to xlutils, xlrd and xlwt as well, but I thought I'd ask here first.
From you comment part C:\Python27\ I deduce that you are on Windows. In that case you are probably better off with using pywin32 and a template .xls or .xlsm file.
Open the file using os.startfile(filename) then connect using workbook = win32com.client.GetObject(filename). The resulting workbook can be filled with the data and written to a new file with `workbook.SaveAs(newfilename).
Anything you do not touch explicitly is preserved. Excel is, of course, somewhat better at that than xlrd, xlwt and xlutils.

Categories

Resources