我希望有人能够为我指明正确的方向,或者举例说明如何使用 xlwt 将以下脚本输出放入 Excel 电子表格中。我的脚本根据需要在屏幕上打印出以下文本,但是我希望将此输出放入 Excel 中,分为时间和值的两列。这是打印的输出..
07:16:33.354 1
07:16:33.359 1
07:16:33.364 1
07:16:33.368 1
到目前为止我的脚本如下。
import re
f = open("C:\Results\16.txt", "r")
searchlines = f.readlines()
searchstrings = ['Indicator']
timestampline = None
timestamp = None
f.close()
a = 0
tot = 0
while a<len(searchstrings):
for i, line in enumerate(searchlines):
for word in searchstrings:
if word in line:
timestampline = searchlines[i-33]
for l in searchlines[i:i+1]: #print timestampline,l,
#print
for i in line:
str = timestampline
match = re.search(r'\d{2}:\d{2}:\d{2}.\d{3}', str)
if match:
value = line.split()
print '\t',match.group(),'\t',value[5],
print
print
tot = tot+1
break
print 'total count for', '"',searchstrings[a],'"', 'is', tot
tot = 0
a = a+1
我已经尝试过使用 xlwt 或 CSV 编写器,但每次我都会遇到困难并恢复到上面的脚本并重试。我希望将 match.group() 和 value[5] 打印到 Excel 工作表上的两个不同列中。
感谢您的宝贵时间...
米克G
最佳答案
您在使用 xlwt 时遇到了哪些问题?就我个人而言,我发现它非常容易使用,记住基本的工作流程:
导入xlwt
使用例如创建电子表格。
my_xls=xlwt.Workbook(encoding=your_char_encoding)
,它返回您的电子表格句柄,用于添加工作表和保存整个文件
将工作表添加到创建的电子表格中,例如。
my_sheet=my_xls.add_sheet("工作表名称")
现在,有了工作表对象,您可以使用sheet_name.write(row,column, value)在其单元格上书写:
my_sheet.write(0,0,"第一列标题") 我的sheet.write(0,1,"第二列标题")
使用电子表格保存整个内容。save('file_name.xls')
my_xls.save("results.txt")
这是一个最简单的工作示例;您的代码当然应该在循环打印数据中使用sheet.write(row,column,value),例如:
import re
import xlwt
f = open("C:\Results\VAMOS_RxQual_Build_Update_Fri_04-11.08-16.txt", "r")
searchlines = f.readlines()
searchstrings = ['TSC Set 2 Indicator']
timestampline = None
timestamp = None
f.close()
a = 0
tot = 0
my_xls=xlwt.Workbook(encoding="utf-8") # begin your whole mighty xls thing
my_sheet=my_xls.add_sheet("Results") # add a sheet to it
row_num=0 # let it be current row number
my_sheet.write(row_num,0,"match.group()") # here go column headers,
my_sheet.write(row_num,1,"value[5]") # change it to your needs
row_num+=1 # let's change to next row
while a<len(searchstrings):
for i, line in enumerate(searchlines):
for word in searchstrings:
if word in line:
timestampline = searchlines[i-33]
for l in searchlines[i:i+1]: #print timestampline,l,
#print
for i in line:
str = timestampline
match = re.search(r'\d{2}:\d{2}:\d{2}.\d{3}', str)
if match:
value = line.split()
print '\t',match.group(),'\t',value[5],
# here goes cell writing:
my_sheet.write(row_num,0,match.group())
my_sheet.write(row_num,1,value[5])
row_num+=1
# and that's it...
print
print
tot = tot+1
break
print 'total count for', '"',searchstrings[a],'"', 'is', tot
tot = 0
a = a+1
# don't forget to save your file!
my_xls.save("results.xls")
一个陷阱:
- 将 native 日期/时间数据写入 xls 对我来说是一场噩梦,就像 Excel 一样 内部不存储日期/时间数据(我也不明白 出),
- 请注意写入单元格的数据类型。对于开始时的简单报告,将所有内容作为字符串传递就足够了, 稍后您会发现 xlwt 文档非常有用。
XLWT 快乐!
关于Python,将打印输出附加到Excel文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23522282/