Skip to content

Instantly share code, notes, and snippets.

@Victor-Palha
Created February 20, 2023 01:04
Show Gist options
  • Save Victor-Palha/4865b436c92ccdf33e895d4f0375cd6e to your computer and use it in GitHub Desktop.
Save Victor-Palha/4865b436c92ccdf33e895d4f0375cd6e to your computer and use it in GitHub Desktop.
Transformar registros SQL Server em uma tabela Excel
import pandas as pd
import pyodbc
from openpyxl import Workbook
from openpyxl.utils.dataframe import dataframe_to_rows
# Conectar ao banco de dados SQL Server
conn = pyodbc.connect('Driver={SQL Server};'
'Server=<server_name>;'
'Database=<database_name>;'
'Trusted_Connection=yes;')
# Consulta SQL para selecionar os registros
sql_query = '''
SELECT coluna1, coluna2, coluna3
FROM nome_da_tabela
WHERE coluna1 > 10
'''
# Ler os dados do SQL Server em um DataFrame do pandas
df = pd.read_sql(sql_query, conn)
# Criar um novo arquivo Excel e adicionar os dados do DataFrame a ele
wb = Workbook()
ws = wb.active
for r in dataframe_to_rows(df, index=False, header=True):
ws.append(r)
# Salvar o arquivo Excel
wb.save('nome_do_arquivo.xlsx')
# Fechar a conexão com o banco de dados SQL Server
conn.close()
@Victor-Palha
Copy link
Author

Descrição

Um script Python que transforma registros SQL em um arquivo Excel

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment