gpt4 book ai didi

python - 将 txt 文件转换为 xls 文件

转载 作者:太空宇宙 更新时间:2023-11-03 16:22:22 25 4
gpt4 key购买 nike

我需要一些帮助来指定 xls 中值的格式。我正在将 txt 文件转换为 xls。

下面是我当前的代码。当我读取 txt 文件时,我需要将值设置为 Int/Float 或 str。 Int 可以,str 也可以,但我无法解决 float 的问题。

例如,

366351.77-6000.00 仍作为 str 插入工作表中。

我不知道问题是在我读取txt文件的内容时,还是在我尝试将txt的字符串内容转换为浮点格式时。

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

最佳答案

使用cell对象的set_explicit_value方法。

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

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

关于python - 将 txt 文件转换为 xls 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38316779/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com