merged cells are broken after load/save using openpyxl - python

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.

Related

Openpyxl-Made changes to excel and store it in a dataframe, how to kill the Excel without saving all the changes and avoid further recovery dialogue?

I need to open and edit my Excel with openpyxl, store the excel as a dataframe, and close the excel without any changes. Are there any ways to kill the excel and disable the auto-recovery dialogue which may pop out later?
The reason I'm asking is that my code worked perfectly fine in Pycharm, however after I packed it into .exe with pyinstaller, the code stopped working, the error said "Excel cannot access the file, there are serval possible reasons, the file name or path does not exist, or the file is being used by another program, or the workbook you are saving has the same name as a currently open workbook.
I assume it is because the openpyxl did not really close the excel, and I exported it to a different folder with the same file name.
Here is my code:
wb1 = openpyxl.load_workbook(my_path, keep_vba=True)
ws1 = wb1["sheet name"]
making changes...
ws1_df = pd.DataFrame(ws1.values)
wb1.close()
Many thanks ahead :)
The following way you can do this. solution
from win32com.client import Dispatch
# Start excel application
xl = Dispatch('Excel.Application')
# Open existing excel file
book = xl.Workbooks.Open('workbook.xlsx')
# Some arbitrary excel operations ...
# Close excel application without saving file
book.Close(SaveChanges=False)
xl.Quit()

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")

Save changes with openpyxl

I am new to python and an using openpyxl to edit an xlsx file. I am having an issue trying to save the original file. It seems that openpyxl keeps making me save the changes as a new xlsx.
Here is the code I am using and get the error TypeError: save() takes exactly 2 arguments (1 given)
import openpyxl
from openpyxl import Workbook
wb = openpyxl.load_workbook('book1.xlsx')
sheet = wb.get_sheet_by_name("Sensor Status")
sheet['I3'] = '=countifs(B:B,"*server*",C:C,"=0")'
sheet['I4'] = '=countifs(B:B,"*server*",C:C,">=0")'
wb.save()
Sir,
You need to add the file name like:
wb.save('book1.xlsx')
Gen Wan's answer is already correct. But, assuming you already did that and you still had an error, this might help you. I had the same problem, and I figured out that it gave me an error because my file was still open in Microsoft Excel while I was trying to save it with openpyxl. When the one same file is opened by two platforms (Which in this case are Microsoft Excel and openpyxl), I think that the priviledge to save the file is prioritized for the Microsoft Excel software, that's why it's declining the save command from openpyxl. Once I closed Microsoft Excel, I no longer had the error and I was able to save the file. I am assuming you had the error because of that too.

'[Errno 13]' Permission denied: Openpyxl and win32com conflict

I'm using win32com to run macros in excel and openpyxl to modify cell values. In the process of debugging, I attempted to create a simplified version of existing code but still ran into the same
[Errno 13] Permission denied:'C:\\Users\\NAME\\Desktop\\old\\Book1.xlsx'.
I believe that the error is caused by the two packages (win32com and openpyxl) opening the same file and, when attempting to save/close, cannot close the instance open in the other package.
When I attempt to save/close with openpyxl before saving/closing with win32com, I run into the permission denied error. This makes sense; Openpyxl probably does not have permission to close the excel instance open through win32com. Code is below:
wb.save(r"C:\Users\NAME\Desktop\old\Book1.xlsx")
xel.Workbooks(1).Close(SaveChanges=True)
However, when I switch the order:
xel.Workbooks(1).Close(SaveChanges=True)
wb.save(r"C:\Users\NAME\Desktop\old\Book1.xlsx")
Excel attempts to save a backup file (randomly named "522FED10" or "35C0ED10", etc.) and when I press save, Excel crashes.
What's the workaround? I was thinking that you could use win32com to run the macros, save under a different filename, then use openpyxl to access that file and edit values. However, this is extremely inefficient (I'm dealing with excel files that have hundreds of thousands of rows of data). I could consider just using win32com, but that would require a revamp of a system.
Simple code:
import openpyxl as xl
import win32com.client
xel=win32com.client.Dispatch("Excel.Application")
xel.Workbooks.Open(Filename=r"C:\Users\NAME\Desktop\old\Book1.xlsx")
wb = xl.load_workbook(r"C:\Users\NAME\Desktop\old\Book1.xlsx")
ws = wb.active
xel.visible = False
xel.Cells(1,1).Value = 'Hello Excel'
ws.cell(row = 1,column = 2).value = "test"
xel.Workbooks(1).Close(SaveChanges=True)
wb.save(r"C:\Users\NAME\Desktop\old\Book1.xlsx")
Current issue
You should definitely not mix win32com and openpyxl operations.
The win32com statement xel.Workbooks.Open() loads the workbook contents into a memory space controlled by an Excel process. The openpyxl xl.load_workbook() statement on the other hand loads the workbook contents into a completely separate memory space controlled by a Python process.
Hence any subsequent win32com commands will do nothing to affect the workbook that's living inside the python-process-controlled memory, and vice versa any openpxyl commands will do nothing to affect the workbook that's living inside the Excel-process-controlled memory.
Solution
You mentioned that you have to run some excel macros. This rules out an openpyxl-only solution. My suggestion would be to use xlwings, which is in essence a powerful and user-friendly wrapper around the win32com API.
Here is a simple example of how you can execute Excel macros and manually update cell values within a single python script:
import xlwings as xw
# Start Excel app (invisibly in the background)
app = xw.App(visible=False)
# Load excel file into active Excel app
book = app.books.open(r"Book1.xlsm")
# Instruct Excel to execute the pre-existing excel macro named "CleanUpMacro"
book.macro("CleanUpMacro")()
# Instruct Excel to write a cell value in the first sheet
book.sheets["Sheet1"].range('A1').value = 42
# Save workbook and terminate Excel application
book.save()
book.close()
app.kill()

merged cells are broken after load/save

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')
how to modify the code so that the file remains in the same format in the new saved file too. Right now with this code the cells which were merged in the original file are broken. How to resolve that because i dont want to destroy the structure in the original file.
I have tried saving the file with the same name then also the same problem is coming. Actually i have to save the file with the same structure but the updated values.Can you guys please help me with this??

Categories

Resources