【问题标题】:extra ' when writng numerics in excel in python在python中用excel写数字时额外的\'
【发布时间】:2022-08-11 02:08:45
【问题描述】:

我有以下代码从文件中读取一些特定值并将它们写入 Excel 工作表。该代码执行我想要的操作,但是在将输入文件中提取的值写入 Excel 工作表时,在它们之前添加了一个额外的 \' 。

这是代码:

from openpyxl import Workbook

wb = Workbook()
ws = wb.active
column_cell_1 = \'A\'
ws[column_cell_1+str(1)] = \'formula_size\' 
column_cell_2 = \'B\'
ws[column_cell_2+str(1)] = \'time\' 

#
counter = 0
file = \"nn.txt\"
with open(file) as openfile:

    for line in openfile:
       s = line.split()
       for i,j in enumerate(s):
           if j == \"total:\":
              counter = counter + 1
              print(s[i])
              total_time = s[i+1].split(\",\")[0]
              print(total_time)
              ws[column_cell_1+str(counter+1)].value = counter
              ws[column_cell_2+str(counter+1)].value = total_time

wb.save(\"nn.xlsx\")

此处输出的 excel 工作表如下所示:

As you can see, there is an extra \' before the numeric value.

当我在终端打印数值时,数字前没有\'。

total:
0.5253981399982877
total:
1.5582128490004834
total:
7.660432515001958
total:
73.78555823400347

如果您能帮助我避免在 excel 表中出现这种额外的 \',我将不胜感激。

    标签: python excel openpyxl xlsxwriter


    【解决方案1】:

    撇号将单元格标记为字符串,这正是您所写的。如果您希望将其视为数字,请使用 float() 将项目转换为浮点数。

    【讨论】:

    • 谢谢!事实上,我忽略了这个小而重要的事情。
    猜你喜欢
    • 2019-04-30
    • 1970-01-01
    • 2022-11-29
    • 1970-01-01
    • 2014-04-18
    • 2020-04-07
    • 2015-01-02
    • 2020-08-23
    • 2014-11-06
    相关资源
    最近更新 更多