使用Python读取SQL Server并保存到Excel中

使用Python连接SQL Server数据库

import pymssql
#自己设置一下host,user, password, database
conn = pymssql.connect(host=ht,
                       user=usr,
                       password=pwd,
                       database=db,
                      # charset用UTF-8读中文会乱码,只读英文可以用UTF-8
                       charset='cp936', 
                       as_dict=False) #有时可以改成True 看情况
cur = conn.cursor()
if not cur:
    raise(NameError,"连接数据库失败")

使用Python连接SQL Server数据库执行简单查询SQL语句

结果返回到resList里,再关闭连接

sql = 'SELECT * FROM TABLE1'
cur.execute(sql)
resList = cur.fetchall()
#查询完毕后必须关闭连接
conn.close()

使用Python连接SQL Server数据库执行非查询SQL语句

cur.execute(sql)
conn.commit()
conn.close()

将数据添加到excel

创建excel表并往里添加数据
Judge whether the file exists
if it exists, open the original file,
otherwise create a new file
:param filename: Target file path 目标路径
:param sheet_index: create a new sheet’s index
:param sheet_name: create a new sheet’s name
:param data: 想要添加进的excel数据 (List)

import openpyxl
def write_xlsx(filepath, filename, sheet_index, sheet_name, data):
    if os.path.exists(filename):
        "the file has already exists"
        wb = openpyxl.load_workbook(filename)
    else:
        "not exists"
        wb = openpyxl.Workbook()
        
    #添加sheet在excel里
    sheet = wb.create_sheet(title=sheet_name, index=sheet_index)
    
    #添加表头,可视情况修改
    sheet.append(['工厂','产品料号','产品类型','子阶料号','Total总量','客户'])
    
    #添加数据进excel表里
    for item in data:
        sheet.append(item)
   
    #保存
    wb.save(filepath+filename)

hint: openpyxl 比 pyxl 可以创建更多的excel行数

  • 3
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值