#!/usr/bin/env python # -*- coding: utf-8 -* import os import xlrd import xlwt import datetime import re from utils.XUtils import XUtils def create_and_write_data_to_excel(p_file_name_prefix=None, p_sheetname=None, p_data=None): wbk = xlwt.Workbook() if p_sheetname is None: p_sheetname = 'Sheet1' sheet = wbk.add_sheet(p_sheetname, cell_overwrite_ok=True) for i in xrange(len(p_data)): for j in xrange(len(p_data[i])): sheet.write(i, j, p_data[i][j]) filename = p_file_name_prefix + datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S") + ".xls" wbk.save(filename) return wbk if __name__ == '__main__': module_path = os.path.dirname(__file__) filename = module_path + '/report_db_20180301_20180302_11881.2_0_100_gdt.txt' """ txt 内容 gdt 20180301 -1.0000 6 2 0.3333 -0.1667 -0.5000 gdt 20180302 -1.0000 4 1 0.2500 -0.2500 -1.0000 gdt SUM 11881.2000 10 3 0.3000 1188.1200 3960.4000 all_acc=10, new_acc=3, r=0.3000 unit_price_all=1188.120000 unit_price_new=3960.400000 #新建一个总的列表 按照每行读取txt,按照空格分割成一个小的列表,append到大的列表,后进行写入excel """ fopen2 = open(filename, 'r') lines = fopen2.readlines() all_list = [] excel_title = [u'广点通',u'日期',u'收入',u'总激活数',u'新增激活数',u'新增激活数/总激活数',u'总激活单价',u'新增激活单价'] all_list.append(excel_title) for line in lines: # charts to list l1 = re.split('[ ]+', line) all_list.append(l1) create_and_write_data_to_excel(p_file_name_prefix='txt_to_excel',p_sheetname='test1',p_data=all_list) print('success')