【问题标题】:Writing from python to an Excel spreadsheet从 python 写入 Excel 电子表格
【发布时间】:2021-04-05 18:04:14
【问题描述】:

我是 Python 新手,我正在尝试将我的数据从 Python 写入 Excel 电子表格。这是我的 python 输出。 https://imgur.com/a/0eyRXvw我希望将python输出中的时间戳数据以https://imgur.com/a/QpxVJse这种格式写入excel电子表格,但问题是我不知道如何从python输出中提取所有数据。对于启动时间戳,我只能提取一个数据值。如何从 python 输出中提取所有值并将其写入 excel 电子表格?

这是我的代码:

import xlwt

pat1 = 'Boot 0x0100M'
pat2 = '2Sync:0 4'
pat3= '2Sync:1 C'
pat_no = 3
matchedline= ''
CE_count = 0
pattern_list = [pat1,pat2,pat3]

book = xlwt.Workbook(encoding = 'utf-8')
sheet1 = book.addsheet("Sheet1", cell_overwrite_ok=True)

sheet1.write(0,0,"spin)
sheet1.write(0,1,"start")
sheet1.write(0,2,"end")
count=0
for i in range(1,9,1):
 sheet1.write(i,0, count)
 count+=1

with open('C:\\Test_Automation\\spinup_spindown.txt') as file:
 for line in file:
  CE_count=1
  for pattern in pattern_list:
   if pattern in line:
    matchedline=line
    print(matchedline)
    timestamp1=matchedline[0:13]
    timestamp2=matchedline[0:13]
    timestamp3=matchedline[0:13]
    if pattern == pat1:
     print(timestamp1)
     sheet1.write(1,1,timestamp1)
    if pattern == pat2:
     print(timestamp2)
    if pattern == pat3:
     print(timestamp3)


book.save("C:\\Test_Automation\\trial.xls")

【问题讨论】:

  • 如果您输出 .csv 然后将其导入 Excel,您的生活会简单得多。

标签: python excel xlwt


【解决方案1】:

回答
在语句sheet1.write(0,0,"spin#) 中有井号 (#),它在 python 中启动注释。这会排除您的代码的其余部分,这可能会导致错误。

另外,我建议将数据写入 CSV 文件,然后将其导入 Excel,而不是直接写入 Excel 文件。 CSV 文件更易于用于数据操作,并且得到各种 Python 数据框库(例如 Pandas)的支持。

【讨论】:

  • 如何将数据写入CSV文件,然后导入excel?
  • 在 Excel 中,您可以转到数据选项卡,然后在获取和转换数据部分单击来自文本/CSV。我个人还没有将数据从 txt 抓取到 csv,但是有多个关于如何这样做的教程。如果您已经有一个用逗号或其他符号分隔不同列的 txt 文件,则可以直接导入,而无需转换为 CSV。
猜你喜欢
  • 2017-05-18
  • 2013-07-11
  • 1970-01-01
  • 1970-01-01
  • 2021-06-28
  • 1970-01-01
  • 2018-12-03
  • 1970-01-01
  • 2021-07-18
相关资源
最近更新 更多