Python, appending printed output to excel file

2019-08-14 19:05发布

问题:

I was hoping someone may be able to point me in the right direction, or give an example on how I can put the following script output into an Excel spreadsheet using xlwt. My script prints out the following text on screen as required, however I was hoping to put this output into an Excel into two columns of time and value. Here's the printed output..

07:16:33.354    1

07:16:33.359    1

07:16:33.364    1

07:16:33.368    1

My script so far is below.

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

I have had a few goes using xlwt or CSV writer, but each time i hit a wall and revert bact to my above script and try again. I am hoping to print match.group() and value[5] into two different columns on an Excel worksheet.

Thanks for your time...

MikG

回答1:

What kind of problems do you have with xlwt? Personally, I find it very easy to use, remembering basic workflow:

  1. import xlwt

  2. create your spreadsheet using eg.

    my_xls=xlwt.Workbook(encoding=your_char_encoding),

    which returns you spreadsheet handle to use for adding sheets and saving whole file

  3. add a sheet to created spreadsheet with eg.

    my_sheet=my_xls.add_sheet("sheet name")

  4. now, having sheet object, you can write on it's cells using sheet_name.write(row,column, value):

    my_sheet.write(0,0,"First column title") my sheet.write(0,1,"Second column title")

  5. Save whole thing using spreadsheet.save('file_name.xls')

    my_xls.save("results.txt")

It's a simplest of working examples; your code should of course use sheet.write(row,column,value) within loop printing data, let it be eg.:

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

A catch:

  • native date/time data writing to xls was a nightmare to me, as excel internally doesn't store date/time data (nor I couldn't figure it out),
  • be careful about data types you're writing into cells. For simple reporting at the begining it's enough to pass everything as a string, later you should find xlwt documentation quite useful.

Happy XLWTing!



标签: python csv xlwt