I need some help with specifying format of values in xls. I am converting a txt file into xls.
Below is my current code. As I read the txt file, i need to put the values as Int/Float or str. Int is ok, as well str, but I can't solve a problem with floats.
366351.77
or -6000.00
, for example, are still being inserted as a str in the sheet.
I don't know if the problem is when i'm reading the content of the txt file or if it is when i tried to convert the string content of the txt to a float format.
import sys
import openpyxl
delimitador, caminho, destino = sys.argv[1], sys.argv[2], sys.argv[3]
xls = openpyxl.Workbook()
sheet = xls.active
sheet.column_dimensions['A']
txt = open(caminho)
def is_float(s):
result = False
if s.count(".") == 1:
if s.replace(".", "").isdigit():
result = True
return result
i = 1
for linha in txt:
coluna = linha.split(delimitador)
ii = 1
for celula in coluna:
cell = sheet.cell(row=i, column=ii)
if is_float(celula):
#cell.value = float(celula.decode('latin-1').encode('utf-8'))
cell.value = 'float'
elif celula.isdigit():
cell.value = int(celula.decode('latin-1').encode('utf-8'))
else:
cell.value = celula.decode('latin-1').encode('utf-8')
ii += 1
i += 1
xls.save(destino)
txt.close()
答案 0 :(得分:1)
Use the set_explicit_value
method of the cell
object.
cell.set_explicit_value(value=your_float, data_type='f')
答案 1 :(得分:0)