Concat,Concatenate,TextJoin, all return '#NAME?'

帅比萌擦擦* 提交于 2019-12-11 15:16:32

问题


so I have this simple code that should insert a formula into a cell:

wb = Workbook()
ws = wb.create_sheet('General')
ws['A1'].value = 'Hello'
ws['B1'].value = 'World'
#Now cell C1 should display 'Hello World'
ws['C1'].value = "=CONCAT(A1,B1)"
#ws['C1'].value = "=CONCATENATE(A1,B1)"
#ws['C1'].value = "=TEXTJOIN(,,A1,B1)"
wb.save('Test.xlsx')

I've manually entered entered the formula in Excel and they work, but when assigned via openpyxl they return #NAME?

The formula in cell C1 checks out, if I select the cell and hit enter or double click it and then click outside, it shows the correct result; I've also tried with but still no luck:

ws['C1'].set_explicit_value("=CONCAT(A1,B1)","f")

回答1:


The problem is that the OOXML specification only covers the formulae that were in the original release and not those that Microsoft has added in subsequent releases.

You can easily check whether a formula is ok:

from openpyxl.utils.formulas import FORMULAE
'CONCAT' in FORMULAE
False
'CONCATENATE' in FORMULAE
True
'TEXTJOIN' in FORMULAE
False

In order to use more recent formulae, these must be prefixed with '_xlfn.'. If there are still problems then you will need to look at the XML source of the relevant files.




回答2:


.Value property explicitly sets the Range's well... value

If you intend on using formula, you should use the .Formula property instead:

ws['C1'].Formula = "=CONCAT(A1,B1)"

should yield the expected result. Feel like it's pretty self-explanatory as to why.


EDIT:

Note, this will produce the expected result "HelloWorld", however it appears you desired the result to be "Hello World" instead.

To achieve the above mentioned result, use this formula instead:

ws['C1'].Formula = "=CONCAT(A1, " ", B1)

Last but not least as @tigeravatar correctly mentioned in the comments, in older Excel version use the formula =CONCATENATE()instead!



来源:https://stackoverflow.com/questions/51287407/concat-concatenate-textjoin-all-return-name

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