如何使用 openpyxl 从 python 中的 xlsx 文件中读取货币符号?
How to read a currency symbol from an xlsx file in python using openpyxl?
我有一个 .xlsx
文件,其中包含一个组织的国际劳动力的工资信息。我正在提取他们的一些细节。一切顺利,除了他们的薪水。
工资值看起来像:£10,000
或 €34000
等。在 excel 文件中,符号是通过格式单元格选项添加的。但是我的代码只读取没有货币符号的实际数字。
下面是我的代码:
import openpyxl
wb = openpyxl.load_workbook("International_Employees.xlsx")
for ws in wb:
for row in iter_rows():
for cell in row:
if str(cell.value) == 'SALARY':
salary = "{1}".format(cell.value, cell.offset(0,1).value)
print(salary)
输出只是:10000
而不是 £10,000
或 £10000
如何让程序也使用 openpyxl
读取符号?
您可以使用 number_format
属性 来查找,这里是您如何实现它的示例:
c = ws['A1']
fmt = c.number_format
print(fmt) # >>> for me: #,##0.00\ "€"
symbol = re.search(r"[€£]", fmt)
if not symbol:
print("no currency")
else:
print(f"{c.value} {symbol.group(0)}") # >>> 1000 €
更新:
更新 2:
for ws in wb:
for row in iter_rows():
for cell in row:
print(cell.value, cell.number_format)
我有一个 .xlsx
文件,其中包含一个组织的国际劳动力的工资信息。我正在提取他们的一些细节。一切顺利,除了他们的薪水。
工资值看起来像:£10,000
或 €34000
等。在 excel 文件中,符号是通过格式单元格选项添加的。但是我的代码只读取没有货币符号的实际数字。
下面是我的代码:
import openpyxl
wb = openpyxl.load_workbook("International_Employees.xlsx")
for ws in wb:
for row in iter_rows():
for cell in row:
if str(cell.value) == 'SALARY':
salary = "{1}".format(cell.value, cell.offset(0,1).value)
print(salary)
输出只是:10000
而不是 £10,000
或 £10000
如何让程序也使用 openpyxl
读取符号?
您可以使用 number_format
属性 来查找,这里是您如何实现它的示例:
c = ws['A1']
fmt = c.number_format
print(fmt) # >>> for me: #,##0.00\ "€"
symbol = re.search(r"[€£]", fmt)
if not symbol:
print("no currency")
else:
print(f"{c.value} {symbol.group(0)}") # >>> 1000 €
更新:
更新 2:
for ws in wb:
for row in iter_rows():
for cell in row:
print(cell.value, cell.number_format)