Python 远程操作&文本转换excel

摘要:
      提高工作效率,完成一个SQL导出EXCEL的功能。虽然MySQL 可以直接生成excel,但是还是想通过python实现。

知识点:

      1,安装paramiko模块,参考:这里或则执行apt-get install python-paramiko,也可以在google上搜索相关文章。
      2,安装xlwt模块,参考这里,安装sudo python setup.py install

参考文章:
     
1,http://www.codecho.com/write-excel-files-with-python-using-xlwt/ 了解xlwt的用法。
      2,http://wangwei007.blog.51cto.com/68019/1058726 了解远程执行命令和上传下载的方法。

脚本:
用法:python txt2xls.py  test

View Code
#!/bin/env python
# -*- encoding: utf-8 -*-
#-------------------------------------------------------------------------------
# Name:        txt2xls.py
# Purpose:     处理SQL生成Excel
# Author:      zhoujy
# Created:     2013-01-11
# update:      2013-01-11
# Copyright:   (c) Mablevi 2013
# Licence:     zjy
# Usage:       python txt2xls.py 生成的excel名字
#-------------------------------------------------------------------------------
import paramiko
import MySQLdb
import datetime
import os
import sys
import xlwt
import getpass

def get_data(conn,query): #从MySQL取数据,导成文本
    query = query + " into outfile '/home/zhoujy/outfile/out.txt'"
    cursor = conn.cursor()
    cursor.execute(query)

def sync_txt(hostname,port,username,password): #同步下载文本
    local_dir=r'/home/zhoujy/outfile/'
    remote_dir=r'/home/zhoujy/outfile/' 
    try :
        t=paramiko.Transport((hostname,port))          
        t.connect(username=username,password=password)          
        sftp=paramiko.SFTPClient.from_transport(t)  
#        files=sftp.listdir(dir_path)          
        files=sftp.listdir(remote_dir)          
        for f in files:
            print ''               
            print '#########################################'                  
            print 'Beginning to download file  from %s  %s ' % (hostname,datetime.datetime.now().strftime('%H:%M:%S'))                
            print 'Downloading file:',os.path.join(remote_dir,f) 
            sftp.get(os.path.join(remote_dir,f),os.path.join(local_dir,f))#下载               
#            sftp.put(os.path.join(local_dir,f),os.path.join(remote_dir,f)) 上传                 
            print 'Download file success %s ' % datetime.datetime.now().strftime('%H:%M:%S')        
            print '##########################################'   
        t.close()
    except Exception :  
        print "connect error!" 

def rm_txt(hostname,port,username,password): #在服务器上执行删除文本
    paramiko.util.log_to_file('paramiko.log')
    s=paramiko.SSHClient()
    s.set_missing_host_key_policy(paramiko.AutoAddPolicy())          
    s.connect(hostname = hostname,port=port,username=username, password=password)          
    stdin,stdout,stderr=s.exec_command('rm /home/zhoujy/outfile/out.txt')          
    print stdout.read()       
    s.close()

def txt2xls(filename,xlsname):  #文本转换成xls
    print 'converting xls ... '
    f = open(filename)
    x = 0
    y = 0
    xls=xlwt.Workbook()
    sheet = xls.add_sheet('sheet1',cell_overwrite_ok=True)
    while True:
        line = f.readline()
        if not line:
            break
        for i in line.split('\t'):
            item=i.strip().decode('utf8')
            sheet.write(x,y,item)
#            xls.save('test.xls')
            y += 1
        x += 1
        y = 0
    f.close()
    xls.save(xlsname+'.xls')

if __name__ == '__main__':
    hostname=raw_input('Enter Host IP   : ')
    port = input('Enter Host port : ')
    username=raw_input('Enter Host User : ')
    password = getpass.getpass('Enter Host Pwd  : ')
    Mport = input('Enter MySQL port : ')
    DBName = raw_input('Enter MySQL DBName: ')
    query = raw_input('Press SQL : ')
    conn = MySQLdb.connect(host=hostname,user='zjy',passwd='Knoj7tweysurvEg-',charset='utf8',db=DBName,port=Mport)
    get_data(conn,query)
    sync_txt(hostname,port,username,password)
    rm_txt(hostname,port,username,password)
    txt2xls('out.txt',sys.argv[1])
    raw_input('按回车结束')

 里面需要注意的是目录的问题,目录要是不存在或则没有权限,则脚本会报错;还有一点是输入中需要都在一行,不能多行,如长的sql不能分行执行。
如果只是需要把文本转换成xls,或则是在服务器上执行命令只需把脚本里面的函数取出来单独创建一个脚本就可以用了。

效果:

生成一个test的EXCEL文件。图上有个问题,在脚本后面的test.xls是不需要.xls后缀的,否则会出现2个。图就不改了。

总结:


~~~~~~~~~~~~~~~ 万物之中,希望至美 ~~~~~~~~~~~~~~~
原文地址:https://www.cnblogs.com/zhoujinyi/p/2857171.html