使用python进行excel自动化操作

作者: 代号孤狼 | 来源:发表于2016-05-30 16:03 被阅读3529次

    使用Python一键生成Oracle性能excel曲线图

    1、cx_Oracle安装与使用

    1.1 python 使用最新3.5.1 64位

    1.2 Oracle 使用11g 32位

    1.3 cx_Oracle使用5.2.1 与11g的Oracle与python一致

    在cx_Oracle下载安装使用时候注意事项:

    • 必须与选用的python与Oracle版本一致
    • 当遇到报错,则需要冷静看一下 各服务 是否已经开启

    1.4 cx_Oracle使用

    import cx_Oracle
    conn=cx_Oracle.connect('JGANG/JGANG@DATABASE')  #建立Oracle连接
    cursor=conn.cursor()                            #建立Cursor光标,用此执行SQL语句
    cursor.execute('select distinct t.stationcode from TARGET_STATION t')
    #执行SQL语句
    row=cursor.fetchall()       #调用cursor.fetchall()一次取完,cursor.fetchone()一次取一行
    
    def GetInOutFlow(staName):    #根据传入的车站名得到对应的车站进出站量
        sqlstr="select t.time,t.innum,t.outnum from TARGET_STATION T where t.stationcode='{0}' order by t.time".format(staName)
        cursor.execute(sqlstr)
        InOutFlow=cursor.fetchall()    #取出对应车站的进出站量
        return InOutFlow
    
    for x in row:
        staName=x[0]        #车站名字
        InOutFlow=GetInOutFlow(staName)
        print(InOutFlow)            #不要直接打印将其保存到excel中
        break
    
    

    2、excel操作使用xlsxwriter模块

    2.1 Python的Excel处理模块:XlsxWriter下载

    2.2 XlsxWriter下载与安装

    • cmd 下 输入 pip install wheel
    • 到XlsxWriter.whl所在文件下,pip install 包名字.whl

    2.3 XlsxWriter使用,使用看这

    workbook  = xlsxwriter.Workbook('filename.xlsx')
    worksheet = workbook.add_worksheet()  #()中可以加入名字
    
    worksheet.write(0, 0, 'Hello Excel')
    
    workbook.close()
    

    2.4 制作折线图

    import cx_Oracle
    import xlsxwriter as xls
    conn=cx_Oracle.connect('JGANG/JGANG@DATABASE')  #建立Oracle连接
    cursor=conn.cursor()                            #建立Cursor光标,用此执行SQL语句
    cursor.execute('select distinct t.stationcode from TARGET_STATION t')
    #执行SQL语句
    row=cursor.fetchall()       #调用cursor.fetchall()一次取完,cursor.fetchone()一次取一行
    #xlsx文件操作
    workbook=xls.Workbook('车站进出站信息.xlsx')
    def GetInOutFlow(staName):    #根据传入的车站名得到对应的车站进出站量
        sqlstr="select t.time,t.innum,t.outnum from TARGET_STATION T where t.stationcode='{0}' order by t.time".format(staName)
        cursor.execute(sqlstr)
        InOutFlow=cursor.fetchall()    #取出对应车站的进出站量
        return InOutFlow
    def Transposition(InOutFlow):          #将InOutFlow转置,并放回
        result=[]
        colTime=[]
        colIn=[]
        colOut=[]
        for row in InOutFlow:
            colTime.append(row[0])
            colIn.append(row[1])
            colOut.append(row[2])
        result.append(colTime)
        result.append(colIn)
        result.append(colOut)
        return result
    
    def Export(InOutFlow,staName):             #将车站的进出站信息保存到xlsx中
        worksheet=workbook.add_worksheet(staName)
        bold=workbook.add_format({'bold':1})
        #添加表头
        headings=['时间','进站','出站']
        worksheet.write_row('A1',headings,bold)
        #添加内容
        worksheet.write_column('A2',InOutFlow[0])
        worksheet.write_column('B2',InOutFlow[1])
        worksheet.write_column('C2',InOutFlow[2])
        #创建新的图表,折线图
        chart=workbook.add_chart({'type':'line'})
        chart.add_series(
            {
             'name':       '={0}!$B$1'.format(staName),
             'categories': '={0}!$A$2:$A${1}'.format(staName,len(InOutFlow[0])+1),
             'values':     '={0}!$B$2:$B${1}'.format(staName,len(InOutFlow[0])+1),
             })
        chart.add_series(
            {
            'name':   [staName,0,2],
            'categories':[staName,1,0,len(InOutFlow[0])+1,0],
            'values':[staName,1,2,len(InOutFlow[0])+1,2],
            })
        #添加表头和xy
        chart.set_title({'name':'{0}站全天进出站量变化趋势'.format(staName)})
        chart.set_x_axis({'name':'时间'})
        chart.set_y_axis({'name':'人数(人)'})
        #Set an Excel chart style. Colors with white outline and shadow.
        chart.set_style(10)
        # Insert the chart into the worksheet (with an offset).
        worksheet.insert_chart('E2', chart, {'x_offset': 25, 'y_offset': 10})
    
    
    for x in row:
        staName=x[0]        #车站名字
        InOutFlow=Transposition(GetInOutFlow(staName))
        #print(InOutFlow)            #不要直接打印将其保存到excel中
        Export(InOutFlow,staName)
    workbook.close()
    
    

    3、读取excel内容,xlrd下载

    3.1 xlrd安装教程

    下载xlrd文件后,解压到一个文件夹,然后cd到该文件夹,python setup.py install 进行安装

    3.2 使用

    import xlrd
    #读取xlxs文件,将车站保存到内存
    filename=r'{0}\车站名.xlsx'.format(currentPath)
    data = xlrd.open_workbook(filename)
    sheetname = data.sheet_names()
    sheet = data.sheet_by_index(0)
    rows = sheet.nrows
    cols = sheet.ncols
    staName=[]
    for row in range(rows):
       staName.append(sheet.row_values(row)[0])
    

    4、结果展示

    进出站变化曲线 全天断面分析 满载率变化

    5、Python操作excel优势

    5.1 python本身语法简单,作为一门脚本语言可以很方便的进行操作

    5.2 python的excel模块强大,直接生成excel图和内容插入

    5.3 若要做好几百张类似的图,不用再跟傻瓜一样去拉图啦!!!

    5.4 可重复使用

    相关文章

      网友评论

      本文标题:使用python进行excel自动化操作

      本文链接:https://www.haomeiwen.com/subject/gsqcdttx.html