#连接SQL server数据库的模块为pyodbc,MySQL需要MySQLdb
import pyodbc
from openpyxl import Workbook
server = 'server name
database = 'database name'
username = 'usename
password = 'password'
driver= '{ODBC Driver 17 for SQL Server}'#对应的数据库版本的驱动
#1433是数据库默认的连接端口,不同的数据库的端口号是不一样的
cnxn = pyodbc.connect('DRIVER='+driver+'; SERVER='+server+'; PORT=1433;DATABASE='+database+'; UID='+username+'; PWD='+ password)
cursor = cnxn.cursor()
script = "SELECT * FROM adi_digital_result_KPImanagement_before"
cursor.execute(script)
#获取查询结果的字段名列表,将数据库的字段名(标题)列表放进columns
columns = [desc[0] for desc in cursor.description]
data = cursor.fetchall()
#新建Excel文件
wb = Workbook()
sheet = wb.active
print(type(sheet))
sheet.title = 'test'
#将列表写入到excel的sheet里
sheet.append(columns)
for j in data:
sheet.append(list(j))
wb.save(r"testsql.xlsx")
网友评论