您好,欢迎来到钮旅网。
搜索
您的当前位置:首页使用Python读取SQL Server并保存到Excel中

使用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行数

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- niushuan.com 版权所有 赣ICP备2024042780号-2

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务