Excel from Python (openpyxl) Issue - python

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

Related

How to split Excel-Data into seperate Worksheets and maintain cell formating with Python 3?

I get a huge Excel-Sheet (normal table with header and data) on a regular basis and I need to filter and delete some data and split the table up into seperate sheets based on some rules. I think I can save me some time if I use Python for that tedious task because the filtering, deleting and splitting up into several sheets is based on always the same rules that can logically be defined.
Unfortunately the sheet and the data is partially color-coded (cells and font) and I need to maintain this formating for the resulting sheets. Is there a way of doing that with python? I think I need a pointer in the right direction. I only found workarounds with pandas but that does not allow me to keep the formatting.
You can take a look at an excellent Python library for Excel called openpyxl.
Here's how you can use it.
First, install it through your command prompt using:
pip install openpyxl
Open an existing file:
import openpyxl
wb_obj = openpyxl.load_workbook(path) # Open notebook
Deleting rows:
import openpyxl
from openpyxl import load_workbook
wb = load_wordbook(path)
ws = wb.active
ws.delete_rows(7)
Inserting rows:
import openpyxl
from openpyxl import load_workbook
wb = load_wordbook(path)
ws = wb.active
ws.insert_rows(7)
Here are some tutorials that you can take a look at:
Tutorial 1
Youtube Video

Why does my header image disappear from my template?

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.

Openpyxl not writing to my Excel spreadsheet

I am trying to write to an Excel worksheet but the code does not do anything. I have the file name right and it correctly detects the only sheet ('Sheet1') but when I try to write to a cell nothing happens. I am running Microsoft Office 365 if that matters.
I have tried
wb = openpyxl.load_workbook('Spendings 2019.xlsx')
ws = wb.active
ws['B3'] = 4
This does not change the Excel file at all when run.
Did you read the docs? You need
print(cell.value)
As explained https://openpyxl.readthedocs.io/en/stable/usage.html
Also, if you are making changes to the spreadsheet, you need to save it

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.

How to append to an existing excel sheet with XLWT in Python

I have created an excel sheet using XLWT plugin using Python. Now, I need to re-open the excel sheet and append new sheets / columns to the existing excel sheet. Is it possible by Python to do this?
After investigation today, (2014-2-18) I cannot see a way to read in a XLS file using xlwt. You can only write from fresh. I think it is better to use openpyxl. Here is a simple example:
from openpyxl import Workbook, load_workbook
wb = Workbook()
ws = wb.create_sheet()
ws.title = 'Pi'
ws.cell('F5').value = 3.14156265
wb.save(filename=r'C:\book2.xls')
# Re-opening the file:
wb_re_read = load_workbook(filename=r'C:\book2.xls')
sheet = wb_re_read.get_sheet_by_name('Pi')
print sheet.cell('F5').value
See other examples here: http://pythonhosted.org/openpyxl/usage.html (where this modified example is taken from)
You read in the file using xlrd, and then 'copy' it to an xlwt Workbook using xlutils.copy.copy().
Note that you'll need to install both xlrd and xlutils libraries.
Note also that not everything gets copied over. Things like images and print settings are not copied, for example, and have to be reset.

Categories

Resources