# -*- coding: utf-8 -*-
import pyodbc
import time
s = time.time()
cnxn = pyodbc.connect(DRIVER='{SQL Server}',SERVER='192.168.12.10',
DATABASE='PM',UID='zls',PWD='zls521')
cursor = cnxn.cursor()
cursor.execute('''
SELECT TOP 1000 [ALLOC_STATUS]
,[DEMAND_NO]
,[XFER_NO]
FROM A
''') #调用游标指针的execute方法执行sql语句
row = cursor.fetchall() #sql语句执行结果的获取,如果需要一次获取多条记录,可以使用cursor.fetchall()方法
#if row:
# print (row)
cnxn.commit()
cnxn.close()
import os
import xlwt
#import sys
#import types
#import xlsxwriter
def set_style(name, height, bold = False):
style = xlwt.XFStyle() #初始化样式
font = xlwt.Font() #为样式创建字体
font.name = name
font.bold = bold
font.color_index = 4
font.height = height
style.font = font
return style
def write_excel():
#创建工作簿
workbook = xlwt.Workbook(encoding='utf-8')
#创建sheet
data_sheet = workbook.add_sheet('201903',cell_overwrite_ok=True)
#列表格式数据
excelData = row
#定义循环下标
index = 0
file_style = xlwt.XFStyle()
for i in excelData:
#每一列的内容(i)
for x, item in enumerate(i):
#下标(x),单元元素(item)
# data_sheet.write(index, x, item, set_style('Times New Roman',220, True))
data_sheet.write(index, x, item, file_style)
index += 1
# sys.exit();
#保存文件
workbook.save('PJDM.xls')
print (os.getcwd())
if __name__ =='__main__':
write_excel()
print ('创建demo.xlsx文件成功')
e = time.time()
print ('用时:{}秒'.format(round(e-s,2)))
使用python的pyodbc库操作sql server 2008并将结果保存为excel形式
最新推荐文章于 2024-07-19 14:41:13 发布