Python信息打印到excel

又要记录信息到文档,还是借用python将信息直接写入excel

1:需要模块xlwt

Link:https://pypi.python.org/packages/source/x/xlwt/xlwt-0.7.5.tar.gz

2:安装

tar zxvf xlwt-0.7.5.tar.gz 
cd xlwt-0.7.5
python setup.py install

交互里面,import xlwt不报错即可~!

3:需要输出到excel里的信息,这里以文件存储,假如是动态获取可以用管道得到命令的输出

lihui@2015 $ cat lihui.txt
lihui = 30
lilei = 28
lucy  = 18
lily  = 30
lixia = 30
whyme = 30
your  = 30

4:写excel的python脚本如下,假如上面输入格式不同,可以修改python里面的正则表达式,总之输入和输出格式可以自己控制;只要保证第一个函数的返回值格式一致就行了

#!/usr/bin/env python
################################
#HuiLi 2015-02-11
################################
import sys
import re
import xlwt

def change_data_type(file, pattern, list):
        try:
                pf_file = open(file, 'r')
        except Exception, e:
                print '%s not found!' %file
                sys.exit(1)
        for file_line in pf_file.readlines():
                file_result = re.match(pattern, file_line)
                if file_result is not None:
                        key = file_result.group(1)
                        value = int(file_result.group(2))
                        my_list = []
                        my_list.append(key)
                        my_list.append(value)
                        list.append(my_list)

        return list

def print_into_excel(list, excel, file_name):
        wb = xlwt.Workbook()
        ws = wb.add_sheet("LiHui")

        heading_xf = xlwt.easyxf('font: bold on; align: wrap on, vert centre, horiz center')
        rowx = 0
        ws.set_panes_frozen(True)
        ws.set_horz_split_pos(rowx+1)
        ws.set_remove_splits(True)
        for i, row in enumerate(list):
                for j, col in enumerate(row):
                        ws.write(i, j, col)
        ws.col(0).width = 256 * max([len(row[0]) for row in list])
        wb.save(excel)


lihui_file = 'lihui.txt'
total_list  = []
string_pattern = '(\w.*)\s=\s(\d+)'
excel_file = lihui_file + '.xls'
data = change_data_type(lihui_file, string_pattern, total_list)
print_into_excel(data, excel_file, lihui_file)

5:执行,输出结果

lihui@2015 /cygdrive/d/work
$ python excel.py

lihui@2015 /cygdrive/d/work
$ ls -l lihui.txt.xls
-rw-r--r--+ 1 lihui None 5632 二月 11 00:59 lihui.txt.xls

P0]`T`H%L~U6L7Q6}MVKGAG

发表回复