I have an excel file – the data in which looks like.
JavaScript
x
2
1
[ ("a", 4, 4,2, 5,32), ("b", 6, 7,2, 7,32), ("c", 6, 7,2, None) ]
2
I want to get float values of cells – in which separator is comma. But when accessing them, a value with a dot is returned. Is it possible to do this with opepyxl or other libraries?
what i tried
JavaScript
1
4
1
ref_workbook = load_workbook('file.xlsx')
2
sheet_ranges = ref_workbook['Sheet']
3
sheet_ranges['C2'].value,# == 4.2, expected 4,2
4
I also tried pandas, but it also formats cells with commas.
Advertisement
Answer
This will set the locale to German, which uses a comma as the decimal separator and a dot as the thousands separator, and then format the float value using this locale.
You can also use ‘fr_FR’ for French, ‘pt_BR’ for Brazilian Portuguese and ‘es_ES’ for Spanish etc.
JavaScript
1
22
22
1
import pandas as pd
2
import locale
3
4
def modify_float_separator(row_num, col_num):
5
value = df.iloc[row_num, col_num]
6
# Check if the value is a float
7
if isinstance(value, float):
8
# Set the locale to German
9
locale.setlocale(locale.LC_ALL, 'de_DE')
10
# Format the float using the German locale
11
formatted_value = locale.format_string("%.2f", value, grouping=True)
12
return formatted_value
13
14
15
# Read the Excel file into a DataFrame
16
df = pd.read_excel('example.xlsx')
17
18
19
print(str(df.iloc[1,0])) # 5.32
20
print(modify_float_separator(1,0)) # 5,32
21
22