Openpyxl throws no errors but no changes to workbook are being made? - openpyxl

I've been trying to make a job finder using beautiful soup, and now want to move what I find into an excel file. But even when I try running the simplest changes to a worksheet, like in the code below, nothing actually changes and there are no errors.
I've tried copying tutorial code from online, as I assumed it's my simple mistake (which it probably is), but there is still no change.
import openpyxl
from openpyxl import Workbook
from openpyxl import load_workbook
wb = load_workbook("PracticeWorkbook.xlsx")
ws = wb.active
ws.cell(row=1, column=1,value='please work')
wb.save("PracticeWorkbook.xlsx")

Your code works for me, bearing in mind that because you're using load_workbook you need to already have 'PracticeWorkbook.xlsx' as an existing file.

Related

Openpyxl not removing sheets completely from Excel Sheet

I was wondering if someone can explain why openpyxl is not removing sheet completely. I am using default openpyxl function. Thought this is deleting the sheet but the traces are still there in the developer tab. If you can help to fix this, I would be very grateful.
`remove_sheet(worksheet)`
While I am now using this alternative approach, but I beleive this is not efficient, since I first delete the sheet, then again use openpyxl to write it
xl = win32com.client.Dispatch('Excel.Application')
book = xl.Workbooks.Open(Filename = file, ReadOnly=False)
xl.Application.Run("delSheets.delSheets")
book.Save()
book.Close()
xl.Application.Quit()
del xl

Python Openpyxl return a sheet name which doesn't exist

In my excel file, I have only three worksheet: "Slot 14", "Data Display", and "Ctrl Value".
When I use openpyxl to load excel file, it returns other worksheet which doesn't exist: ['Slot 14', 'DETAILNO-14', 'DETAIL-14', 'PNO-14', 'DATA-14', 'Data Display', 'Ctrl Value']
Following is my code
filepath=r'D:\Users\chshiu\Desktop\filename.xlsx'
wb = openpyxl.load_workbook(filepath)
wb.get_sheet_names()
I don't think there is something wrong in my code. I am wondering maybe the problem is from excel file itself? I have VBA code inside the excel file.
More information:
I use Python3 in windows.
Because openpyxl cannot load xls file now so I save my original xls file into xlsx file.
It's possible that your file contains hidden sheets. Older versions of Excel use things called Macrosheets for some of the GUI controls. openpyxl just reports what it finds.

Python XlsxWriter Protect Worksheet

How to protect an excel worksheet by allowing sort autofilter using python xlsxwriter
i tried the following code
wb = xlsxwriter.Workbook('test.xlsx')
ws = wb.add_worksheet('TEST')
ws.protect('abcd#09',{'sort':True,'autofilter':True})
/* Data Written to ws*/
wb.close()
That code works but may not be doing what you expect. When I ran it I got the following that shows the sort and autofilter enabled:
If you want to have them protected then just leave them in the default/false condition.

OpenPyXL always return None for a cell with hyperlink

(My ultimate purpose is to append clickable cells to existing XLSX.)
I use the code below to extract the cell's display value and the hyperlink.
from openpyxl import load_workbook
xlsFile='hello.xlsx'
wbook = load_workbook(xlsFile)
wsheet1= wbook.get_sheet_by_name('mysheet')
cell1 = wsheet1.cell('A1')
print cell1.value
print cell1.hyperlink
print wsheet1['A1'].value
print wsheet1['A1'].hyperlink
But it returns the following things:
URL1
None
URL1
None
Why the hyperlink always None? I did add hyperlink manually for cell A1 and the hyperlink works in Excel 2013.
Unfortunately, it's a bug.
It's a bug in 2012...
Some related thread:
Extracting Hyperlinks From Excel (.xlsx) with Python
Some details of my experiment with hyperlink. I am using OpenPyXL 2.3.3.
I can add hyperlink to cells.
from openpyxl import load_workbook
xlsFile='hello.xlsx'
wbook = load_workbook(xlsFile)
wsheet1= wbook.get_sheet_by_name('mysheet')
cell1 = wsheet1.cell('A1')
cell1.hyperlink = r'http://www.example.com'
cell1.value=r'XXX'
wbook.save(xlsFile)
But I cannot load the XLSX file and read the hyperlink just as my question said.
And If I just load and re-save the XLSX file, ALL existing hyperlinks will be lost. Yeah!
from openpyxl import load_workbook
xlsFile='hello.xlsx'
wbook = load_workbook(xlsFile)
wbook.save(xlsFile)
A workaround!
Use the formula with OpenPyXL.
My purpose is to append clickable cells to existing XLSX file. Since hyperlink doesn't work. I use the formula =HYPERLINK(url, displayText) instead. And luckily, the formula is not lost like previous experiment 3.
from openpyxl import load_workbook
xlsFile='hello.xlsx'
wbook = load_workbook(xlsFile)
wsheet1= wbook.get_sheet_by_name('mysheet')
cell1 = wsheet1.cell('A2')
cell1.value=r'=HYPERLINK("http://www.example.com","XXX")'
wbook.save(xlsFile)
Other (failed) options I tried:
I looked into the XlsxWriter. But it explicitly says it cannot modify existing XLSX file. So it cannot be used for appending.
I also looked into the xlrd/xlwt/xlutils, unfortunately, if you want to edit an existing excel, you have to use xlrd to load it as a read-only workbook, and then use xlutils to convert(copy) it into a writable workbook. And BANG! during the copy, something will be lost which includes the HYPERLINK formula. According to its doc string, this is a known limitation:
# Copyright (c) 2009-2012 Simplistix Ltd
#
# This Software is released under the MIT License:
# http://www.opensource.org/licenses/mit-license.html
# See license.txt for more details.
from xlutils.filter import process,XLRDReader,XLWTWriter
def copy(wb):
"""
Copy an :class:`xlrd.Book` into an :class:`xlwt.Workbook` preserving as much
information from the source object as possible.
See the :doc:`copy` documentation for an example.
"""
w = XLWTWriter()
process(
XLRDReader(wb,'unknown.xls'),
w
)
return w.output[0][1]
And also, xlwt doesn't support XLSX, only supports XLS. That's another reason I decided not to use it.

openpyxl data_only gives only a none answer when storing a variable

So basically what I am trying to do is read in some input variables from an excel workbook and write them into some Output Model cells. Then I save the workbook to try to update the data in the Output Model. Since my Output Model cells are formulas I try to reload the workbook as a read data_only and then grab those cells and store them on a separate sheet. Then I save the workbook one more time.
The problem is the values I try to grab (LS, Sales, TPLH) in the data_only loaded workbook reads out as none instead of the values that I need. I eventually want to make this into a loop to iterate over a bunch of input variables, but I wanted to try it with just one set to begin with.
If anyone knows of a better way to do this or what I am doing wrong please let me know! I appreciate any and all feedback.
Here is my code:
from openpyxl import load_workbook
wb2 = load_workbook("Z:\\PythonFiles\\testexcel.xlsx")
sh2 = wb2.get_sheet_by_name("Output Model")
sh= wb2.get_sheet_by_name('OptimizationData')
ForeCast = sh.cell(row=3, column=2).value
sh2.cell(row=3, column=6).value=ForeCast
wb2.save("Z:\\PythonFiles\\testexcel.xlsx")
wb = load_workbook("Z:\\PythonFiles\\testexcel.xlsx", data_only =True)
sh3 = wb.get_sheet_by_name("Output Model")
sh4 = wb.get_sheet_by_name("OptimizationData")
LS=sh3.cell(row=11, column=3).value
Sales = sh3.cell(row=12, column=3).value
TPLH = sh3.cell(row=13, column=3).value
sh4.cell(row=3, column=7).value=LS
sh4.cell(row=3, column=8).value=Sales
sh4.cell(row=3, column=9).value=TPLH
wb.save("Z:\\PythonFiles\\testexcel.xlsx")
Openpyxl will never calculate the result of a formula. It is entirely dependent upon another application having done that. It also means that such values are stripped from a workbook when it is passed through openpyxl. This happens as soon as you save wb2. If you want to access those values then you need to open wb in data-only mode first.