处女作输入sql通过python脚本导出 数据

# -*- coding: utf-8 -*-

import os, sys, codecs, getopt, time, datetime, socket, json, math
from DBUtils.PooledDB import PooledDB
import logging, logging.handlers
import xdrlib, xlrd, xlwt
from xlrd import open_workbook
from xlwt import *
from xlutils.copy import copy
from xlutils.styles import Styles

import pymysql

CONSOLE_LEVEL = logging.INFO
FILENAME = "export.xls"

handler = logging.StreamHandler()
handler.setLevel(CONSOLE_LEVEL)
handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
console = logging.getLogger()
console.setLevel(CONSOLE_LEVEL)
console.addHandler(handler)

sql = input("please input sql:")
targetPath = os.path.join(os.path.abspath(os.path.dirname(__file__)), FILENAME)


def export():
    wb = xlwt.Workbook(encoding='utf-8')  # 创建对齐配置
    al = Alignment()
    al.horz = Alignment.HORZ_CENTER
    al.vert = Alignment.VERT_CENTER
    alr = Alignment()
    alr.horz = Alignment.HORZ_RIGHT
    alr.vert = Alignment.VERT_CENTER
    # 创建边框配置
    borders = Borders()
    borders.top = Borders.THIN
    borders.left = Borders.THIN
    borders.right = Borders.THIN
    borders.bottom = Borders.THIN
    # 创建样式
    style = XFStyle()
    style.alignment = al
    style.borders = borders

    line = 0
    sheet = wb.add_sheet("sheet")
    sheet_row = sheet.row(line)

    # 打开数据库连接
    db = pymysql.connect("localhost", "root", "123456", "xxx")

    # 使用 cursor() 方法创建一个游标对象 cursor
    cursor = db.cursor()

    # 使用 execute()  方法执行 SQL 查询
    cursor.execute(sql)


    # 使用 fetchone() 方法获取单条数据.fetchmany()查询多条数据,fetchall()查询全部数据
    rows = cursor.fetchall()
    fields = cursor.description

    for x in range(len(fields)):
        sheet_row.write(x, str(fields[x][0]), style=style)

    for row in rows:
        line += 1
        sheet_row = sheet.row(line)
        for x in range(len(fields)):
            sheet_row.write(x, str(row[x]), style=style)

    wb.save(targetPath)
    cursor.close()
    db.close()

export()

 

转载于:https://my.oschina.net/fengshuzi/blog/1114022

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值