数据库
首页 > 数据库> > PYTHON 连接SQL2008 导出到EXCEL

PYTHON 连接SQL2008 导出到EXCEL

作者:互联网

#import pymssql
from datetime import datetime
import pyodbc
import os
current_dir = os.path.abspath(os.path.dirname(__file__))+"\\"
cnxn = pyodbc.connect(DRIVER='{SQL Server}',SERVER='SQL2008服务器实例名称',DATABASE='数据库名称',UID='sa',PWD='SA登录密码')

import xlwt
def export_excel(table_name):
    aa=datetime.now().strftime('%Y%m%d%H%M%S')+"1班"
    cur = cnxn.cursor()
    sql = "select xsxm,xscj,sj from %s where xsbj='2020级计算机1班'" % table_name
    cur.execute(sql)  # 返回受影响的行数
    
    fields = [field[0] for field in cur.description]  # 获取所有字段名
    all_data = cur.fetchall()  # 所有数据
    
    # 写入excel
    book = xlwt.Workbook()
    sheet = book.add_sheet('sheet1')
    
    for col,field in enumerate(fields):
        sheet.write(0,col,field)
    
    row = 1
    for data in all_data:
        for col,field in enumerate(data):
            sheet.write(row,col,field)
        row += 1
    book.save(current_dir+"%s.xls" % aa)
    

if __name__ == '__main__':
    
    export_excel("xsxx")

 

标签:__,sheet,SQL2008,PYTHON,EXCEL,field,import,col,cur
来源: https://www.cnblogs.com/xkdn/p/14022747.html