【Python系列】excel读写操作以及对应插件xlwd/xlrd安装方法

Date: 2018.5.30


1、参考

https://blog.csdn.net/qq_16103331/article/details/51374497
https://blog.csdn.net/momaojia/article/details/65448071
https://blog.csdn.net/huangzhijie3918/article/details/51393437
https://www.cnblogs.com/beginner-boy/p/7239696.html
https://blog.csdn.net/maliao1123/article/details/52474949

2、xlwd、xlrd安装方法

安装比较简单。
1、从http://pypi.python.org/pypi/xlwt 下载 xlwt-1.0.0.tar.gz;

2、从http://pypi.python.org/pypi/xlrd下载 xlrd-0.9.4.tar.gz;

3、将包解压缩;

4、在win7下运行,

cmd  

切换到对应的解压缩路径

F:  
cd xlrd-0.9.4 

5、安装

setup.py install 

xlwt同理。

3、excel读写操作

(1) 导入模块

  import xlrd
  import xlwd

(2) 新建一个excel

file=xlwt.Workbook(encoding='utf-8',style_compression=0)  

(3) 新建一个sheet工作簿

sheet=file.add_sheet('data')  

(4)向sheet中写数据

sheet.write(1,1,line)  

向第一行第一列单元格中写入line中的内容
(5)保存excel文件

file.save('excel.xls')
4、实战

实现功能:将文本文件中的3列数据写入excel文件中

import os
import sys
import re
import xlwt
import xlrd

allfiles = []
def get_all_file(rawdir):
      for root,dirs,files in os.walk(rawdir):
            for f in files:
                #print f
                if(re.search('test.txt',f)):
                   print f
                   allfiles.append(os.path.join(root,f))
            for dirname in dirs:
                get_all_file(os.path.join(root,dirname))
      allfiles.sort(key=str.lower)
      return allfiles

def make_all_dir(path):
      path = path.strip()
      isExist = os.path.exists(path)
      if (not isExist):
            os.makedirs(path)
            print(path+' Successful Create!')
            return True
      
def autoExtract(file ,excel_file):

    txt = open(file,'r')
    excel = xlwt.Workbook(encoding='utf-8', style_compression=0)
    sheet = excel.add_sheet('statistics')

    lines = txt.readlines()
    i=0
    for line in lines:
        line.rstrip(' ')
        out = re.split('[,]',line)       
        print out
        sheet.write(i,0,out[0])
        sheet.write(i,1,out[1])
        sheet.write(i,2,out[2])
        i = i+1
    excel.save(excel_file)
    return 0

if __name__ == '__main__':
    if(len(sys.argv) < 3):
        print("Usage: autoExtractToExcel.py targetDir outResult\n")
        sys.exit(1)
    targetDir = sys.argv[1]
    outResultDir = sys.argv[2]
    if(not os.path.exists(outResultDir)):
          make_all_dir(outResultDir)
    excel_file = outResultDir + "/"+"_result.xls"
    allfiles = get_all_file(targetDir)
    for file in allfiles:
        autoExtract(file,excel_file)

    sys.exit(0)

后续改进:如何有效提取含有多个空格的文本中的数据?

你可能感兴趣的:(【Python编程】)