How to use Excel defined names in Python to obtain the values? - python

I have the following set of code which is trying to find the text in a cell within an excel worksheet called 'Input'. I am using openpyxl.
The cell uses a defined name in excel called 'Rperiod'. I can call the text by specifying the sheet and cell range directly, but I'm wondering if there is a way to use the defined_names function to keep it dynamic.
Rperiod = wb.defined_names['Rperiod']
Rperiod.value
This results in 'Input!$F$8' but then I can't workout if it is possible to use this result to get the text. The static method is:
input_sheet = wb.get_sheet_by_name('Input')
Rperiod_cell = input_sheet['F8']
Rperiod_cell.value
This returns the correct result 'Quarterly' but I obviously want to do this without directly specifying the cell 'F8' or the sheet 'Input'.
Any help is greatly appreciated!

Related

Make Excel Cell value Variable in Python Using Pandas

I have looked for a while on this one but can't seem to find out how to pick a specific cell value in an excel worksheet and assign it to variable in python. I get a Traceback Error with the code below.
I have a number of work rules I want to assign as variables in python that are stored in an cells within an excel workhseet.
(work rules[4][2] is how I am trying to make the cell value into a variable.
Code:
work_rules = pd.read_excel(
'D:\\Personal Files\\Technical Development\\PycharmProjects\\Call Center Headcount Model\\Call Center Work Rules.xlsx',
sheet_name='Inputs')
historical_start_date = work_rules[4][2]
print(historical_start_date)
Found it:
Use the iloc method on the excel object: work_rules.iloc(4, 2)

Using a reference to create a new object in python

I think that this is a pure Python "problem" but some context is needed:
I'm creating a simple Python script to modify ods documents with the library ezodf.
Ods files are similar to Excel documents: a table containing cells that contain value, format, etc.
The source comes from a template that I can't edit since I don't have the access to it and I need new cells with the same format as the ones I have but creating them with ezodf is not an option.
Let's work just with column "A" to simplify
I want cell["A5"] to be a copy of cell["A3"] but if I do
cell["A5"] = cell["A3"]
the cell "A3" moves to "A5" instead of filling cell "A5" with a copy and I can no longer access "A3"
My question is, what can I do to assign a cell["A5"] to a copy of "A3" instead of assigning it to "A3"?
Thanks to Maksymilian for showing me this module, I've tryied with cell["A5"] = copy.deepcopy(cell["A3"]) to create new cells based on the original "A3" cell and it works like a charm

How to insert array formula in an Excel sheet with openpyxl?

I'm using OpenPyxl to create and modify an Excel sheet.
I have the following formula in Excel:
=(SUM(IF(LEFT(Balances!$B$2:$B$100,LEN($B4))=$B4,Balances!$D$2:$D$100)))
This formula which is an "array formula" is working but in order to write it by hand, I have to finish with CTRL+SHIFT+ENTER (because it's an array formula).
This transform then the formula as follow:
{=(SUM(IF(LEFT(Balances!$B$2:$B$100,LEN($B4))=$B4,Balances!$D$2:$D$100)))}
I want to be able to write this formula via OpenPyxl with the following code:
sheet.cell(row=j, column=i).value = '{=(SUM(IF(LEFT(Balances!$B$2:$B$100,LEN($B4))=$B4,Balances!$D$2:$D$100)))}'
However, it doesn't work. OpenPyxl can't manage it. It give me the formula written but not working.
I could do it with XLSX Writer
https://xlsxwriter.readthedocs.io/example_array_formula.html
However XLSX writer doesn't work with already created files.
I don't see which path to follow.
Use the worksheet.formula_attributes to set the array formula. Place the formula in the desired cell, A1 for this example. Then set the formula_attributes to the cell range you want to apply the formula to.
ws["A1"] = "=B4:B8"
ws.formula_attributes['A1'] = {'t': 'array', 'ref': "A1:A5"}
In case solution provided above does not work, check whether you are using english name of functions in your formulae.
In my case I have been using czech function name and although formulae works if inserted manually, it did not work when inserted via openpyxl.
Switching to english name of the function solved the issue!
In my case the formula was using arrays for intermediate results before summarizing with a MAX. The formula worked OK when typed in but not when inserted via openpyxl. Office 365 version of Excel was inserting the new implicit intersection operator, #, incorrectly.
formula: ="Y" & MAX(tbl_mcare_opt[Year]*(tbl_mcare_opt[Who]=[#Who])*(tbl_mcare_opt[Year]<=intyear(this_col_name())))
It turns out that the properties needed to be set, as above. This allowed Excel to correctly interpret the formula. In my case the ref turned out to be just the single cell address.
I was able to determine that the formula was using dynamic arrays with a regex. If it was then I added the formula properties.
# provision for dynamic arrays to be included in formulas - notify excel
if is_formula(values[cn]):
regex_column=r'[A-Za-z_]+(\[\[?[ A-Za-z0-9]+\]?\])'
pattern=re.compile(regex_column)
matches=pattern.findall(values[cn])
if len(matches): # looks like a dynamic formula
address=get_column_letter(cix)+str(rix)
ws.formula_attributes[address]={'t':'array','ref': address}

How to copy a formula from one gsheet to another using python?

I'm not sure if this is possible. I have tons of spreadsheet, and the formulas need to be updated. How do I copy a formula from one cell or a group of cells to another? I've used gspread and it seems it can only do values. I need python to basically paste formulas on hundreds of sheets for me, without me opening each individually and copy and pasting the formulas.
Does anybody have a generic solution for copying and pasting formulas? This is pretty important, you would think someone can do it.
Update 19 July 2018:
Here's how you do it:
# Get the formula value from the souce cell:
formula = wks.acell('A2', value_render_option='FORMULA').value
# Update the target cell with formula:
wks.update_acell('B3', formula)
(this works since gspread 3.0.0 which uses Sheets API v4.)
Original answer below:
To access a formula value, you need to use the input_value attribute of a cell object.
Here's an example. (I'm skipping the initialization step. Let's assume you've already opened a spreadsheet and wks is referring to you worksheet object.)
# To copy a formula from a single cell (say, A2) to another cell (B3)
# use the input_value property
formula = wks.acell('A2').input_value
# then paste the value to a new cell
wks.update_acell('B3', formula)
For a group of cells, you'd want to use a wks.range() method to get cell objects. Then you can get formula values via input_value as in the code above. See the example on the GitHub.

How to Check the cell from excel which has formula using python

I Want to access the cell which has formula from the excel workbook.Actually my python script is working fine only to read the data from excel, but i need that only the cell which has formula and to print that cells only
An example would be really appreciated..........
Two things that could help you solve the problem:
There's a typo: HasForumla instead of HasFormula
e is a string, not a cell object, so e.HasFormula won't work.
You probably want to use
e = sheet.cell(row,17)
to access the Cell object at that position. I'm not sure where you got your HasFormula attribute from, though - couldn't find it in the docs.
Edit:
I just looked at the README for the current distribution where it's stated that
xlrd will safely and reliably ignore any of these if present in the
file:
[...]
Formulas (results of formula calculations are extracted, of course).
[...]

Categories