Alexandr
Alexandr

Reputation: 48

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.

Upvotes: 0

Views: 215

Answers (3)

Ánh Lê
Ánh Lê

Reputation: 11

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()

print(table_heading)
print(table_data)

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']]

Upvotes: 1

Vatsal Patel
Vatsal Patel

Reputation: 26

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

Upvotes: 1

CaptainException
CaptainException

Reputation: 96

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

print(my_number)
print(type(my_number))

Output:

(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(".", ",")
print(my_number)
print(type(my_number))

Output:

4,2
<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.

Upvotes: 1

Related Questions