Converting a txt file to xls file

时间:2016-07-11 21:51:01

标签: python excel type-conversion

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

2 个答案:

答案 0 :(得分:1)

Use the set_explicit_value method of the cell object.

cell.set_explicit_value(value=your_float, data_type='f')

Docs: https://openpyxl.readthedocs.io/en/default/api/openpyxl.cell.cell.html#openpyxl.cell.cell.Cell.set_explicit_value

答案 1 :(得分:0)

首先,尼卡鲁斯,你的帮助解决了我的问题。

这是我的最终代码,现在正在将值(值,帐户,索引..)作为数字正确添加到工作表中,其他值作为(日期,描述...)添加as String

FinalCode