zoukankan      html  css  js  c++  java
  • 使用python批量导入txt导入excel表格(公司电脑设备ip和人员统计)

    #!/bin/env python
    # -*- encoding: utf-8 -*-
    import datetime
    import time
    import os
    import sys
    import xlwt #需要的模块
    import re
    from xlutils.copy import copy
    import xlrd
    
    def txt2xls(filename,xlsname):  #文本转换成xls的函数,filename 表示一个要被转换的txt文本,xlsname 表示转换后的文件名
        print 'converting xls ... '
        #m = re.split('.', filename)
    
        f = open(filename)   #打开txt文本进行读取
        ip = filename
        m = re.match(r'(.*)..{3}', ip)
        ip = m.group(1)
        #xls = xlrd.open_workbook(gConst['xls']['xlsname'])
        xls = xlrd.open_workbook(xlsname)
        newxls = copy(xls)
        newx = newxls.get_sheet(0)
        y = 0
        newx.write(x,y,ip)
        y = 1
        print x,y,filename
        while True:  #循环,读取文本里面的所有内容
            line = f.readline() #一行一行读取
            if not line:  #如果没有内容,则退出循环
                break
            for i in line.split('	'):#读取出相应的内容写到x
                if i == '
    ':break
                if i == '':continue
                try:
                    item=i.strip().decode('utf8')
                except:
                    item=i.strip().decode('GBK')
                if item == (u'操作系统'):break
                if item == (u'CPU'):break
                if item == (u'RAM'):break
                if item == (u'主板'):break
                if item == (u'图像'):break
                if item == (u'硬盘'):break
                if item == (u'光盘驱动器'):break
                if item == (u'音频'):break
                newx.write(x,y,item)
                y += 1 #另起一列
                #x += 1 #另起一行
                #y = 0  #初始成第一列
        f.close()
        newxls.save(xlsname)
        #exit(0)
        #xls.save(xlsname+'.xls') #保存
    
    if __name__ == "__main__":
        x = 1                #在excel开始写的位置(y)
        y = 0                #在excel开始写的位置(x)
        for i in range(101,151):
            filename = repr(i) + '.txt'
            xlsname = 'ip1.xls'
            try:
                txt2xls(filename,xlsname)
                x += 1
            except IOError, e:
                print e
                pass
            
  • 相关阅读:
    认识“委托”
    程序员的修炼之道:从小工到专家(一)
    知识的使用 与 知识的内化
    VB.Net中 Module 的前世今生
    memcached
    C#知识
    Android之垂直显示TextView
    Android开发之各个语言
    Android之hint提示字体大小修改,显示完全
    Android 之计算控件颜色透明度
  • 原文地址:https://www.cnblogs.com/jackyshan/p/3433104.html
Copyright © 2011-2022 走看看