Openpyxl not writing to my Excel spreadsheet - python

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

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

How to change sheet names without losing graph reference with openpyxl

I'm trying to write some code that will change sheet names in an excel file based on the data in another excel file.
At first this worked fine;
Sheet_names = "A","B","C","D"
wb = openpyxl.load_workbook(file_name.xlsx)
for i in range (1, len(Sheet_names)):
Name_change = wb["Sheet{}".format(str(i))]
wb.active = Name_change
Name_change.title = "{}".format(Sheet_names[i])
wb.save((file_name.xlsx))
wb.close()
But for some reason (I'm unsure what I've changed) a graph within the excel file isn't updating. So the data reference is still to Sheet1, Sheet2 etc.
Im also getting a warning message that there are external links - I guess it's assuming the sheet references are external? The excel file comes from a template that's copied across.
Changing it manually isn't an option, Is having Openpyxl recreate the graph for every sheet the only option?
Out of ideas, help!

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

openpyxl.load_workbook(file, data_only=True doens't work?

Why does x = "None" instead of "500"?
I have tried everything that I know and searched 1 hour for answer...
Thank you for any help!
import openpyxl
wb = openpyxl.Workbook()
sheet = wb.active
sheet["A1"] = 200
sheet["A2"] = 300
sheet["A3"] = "=SUM(A1+A2)"
wb.save("writeFormula.xlsx")
wbFormulas = openpyxl.load_workbook("writeFormula.xlsx")
sheet = wbFormulas.active
print(sheet["A3"].value)
wbDataOnly = openpyxl.load_workbook("writeFormula.xlsx", data_only=True)
sheet = wbDataOnly.active
x = (sheet["A3"].value)
print(x) # None? Should print 500?
From the documentation
openpyxl never evaluates formula
Documentation says:
data_only controls whether cells with formulae have either the formula
(default) or the value stored the last time Excel read the sheet.
So, if you have not used Excel to open that .xlsx file(writeFormula.xlsx) once, Excel won't have any data to store then. As a result, your program will return a NoneType value.
If you want your program return '500', you should manually open 'writeFormula.xlsx'. Then, annotate the file creation part of your program. You will get '500'.
I have already tried it. And it works. Tell me if you have a different oppinion. Thanks.
There is an easy way to launch excel and get the formula values updated.
Sample Code Snippet
import win32com.client as win32
excel = win32.gencache.EnsureDispatch('Excel.Application')
workbook = excel.Workbooks.Open(inputFile)
workbook.Save()
workbook.Close()
excel.Quit()
# And for reading the data back we can use data_only mode as True.
oxl = openpyxl.load_workbook(inputFile,data_only=True)
Check the format of the cell in Excel.
I was running into this issue as well. The documentation indicated that you would have to open up the workbook through the excel application and resave it, then the value would return as the last calculated one. Such as
I did that and I still got 'None' as my return.
As with many excel/vba issues, it turned out it was a format issue. I had the cell formatted as 'Accounting' instead of 'Number.' After changing it to number, it worked.
I just have the same questions. The solution is open the xlsx file manually and close it, then click save. After this operation, you can try the wbDataonly programming part and get the data 500

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