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

对着背影说爱祢 提交于 2019-12-11 08:56:43

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/41992091/how-to-copy-a-formula-from-one-gsheet-to-another-using-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!