我希望有人能够指出我正确的方向,或者举例说明如何使用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编写器,但每次我碰壁并将bact恢复到上面的脚本并再试一次。我希望在Excel工作表上将match.group()和value [5]打印到两个不同的列中。
感谢您的时间......
MikG
答案 0 :(得分:3)
xlwt有什么问题?就个人而言,我发现它很容易使用,记住基本的工作流程:
import xlwt
使用例如
创建电子表格 my_xls=xlwt.Workbook(encoding=your_char_encoding)
,
返回用于添加工作表和保存整个文件的电子表格句柄
使用例如为创建的电子表格添加工作表。
my_sheet=my_xls.add_sheet("sheet name")
现在,拥有工作表对象,您可以使用sheet_name.write(行,列,值)在其上写入单元格:
my_sheet.write(0,0,"First column title")
my sheet.write(0,1,"Second column title")
使用spreadsheet.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")
一个问题:
快乐的XLWTing!