How to get data from excel file 'as is' using openpyxl?


I have an excel file – the data in which looks like.

[   ("a", 4, 4,2, 5,32),   ("b", 6, 7,2, 7,32),   ("c", 6, 7,2, None) ]

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

ref_workbook = load_workbook('file.xlsx')
sheet_ranges = ref_workbook['Sheet']         
sheet_ranges['C2'].value,# == 4.2, expected 4,2

I also tried pandas, but it also formats cells with commas.

Asked By: Alexandr



That’s because floats always use points in programming. A comma is only used as a delimiter. If you were to use a comma to assign a value to a float you would create a tuple with two integer values instead.

my_number = 4,2



(4, 2)
<class 'tuple'>

If you want the numbers with a comma as a delimiter you need to convert them to a string and replace the comma with a point.

my_number = 4.2

my_number = str(my_number).replace(".", ",")


<class 'str'>

Should you need to use the numbers for calculations inside your program you need to keep them as floats and convert them to string once your done, you cannot use them as a string in calculations, that will cause errors.

Answered By: CaptainException

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.

import pandas as pd
import locale

def modify_float_separator(row_num, col_num):
    value = df.iloc[row_num, col_num]
    # Check if the value is a float
    if isinstance(value, float):
        # Set the locale to German
        locale.setlocale(locale.LC_ALL, 'de_DE')
        # Format the float using the German locale
        formatted_value = locale.format_string("%.2f", value, grouping=True)
        return formatted_value

# Read the Excel file into a DataFrame
df = pd.read_excel('example.xlsx')

print(str(df.iloc[1,0])) # 5.32
print(modify_float_separator(1,0)) # 5,32

Answered By: Vatsal Patel

I used pandas to get the data from excel and the result is the float values of the cells – where the delimiter is comma

import pandas as pd

read_file = pd.read_excel('name_file')
table_data = read_file.values.tolist()
table_heading = read_file.columns.values.tolist()


the result i got:

['ID', 'Name', 'code']
[[1, 'a', '1,2'], [2, 'b', '1,3'], [3, 'c', '1,4'], [4, 'd', '1,5'], [5, 'e', '1,6']]
Answered By: Ánh Lê
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.