Created
February 20, 2023 01:04
-
-
Save Victor-Palha/4865b436c92ccdf33e895d4f0375cd6e to your computer and use it in GitHub Desktop.
Transformar registros SQL Server em uma tabela Excel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Descrição
Um script Python que transforma registros SQL em um arquivo Excel