Untitled Note
By: Anonymous10/27/202312 views Public Note
import pyodbc
import openpyxl
import io
# Connect to SQL Server DB
cn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=ServerName;DATABASE=DatabaseName;UID=UserName;PWD=Password')
cursor = cn.cursor()
# Fetch the contents of the given table
cursor.execute('SELECT * FROM TableName')
table_data = cursor.fetchall()
# Save the table data as Excel
wb = openpyxl.Workbook()
ws = wb.active
ws.title = 'TableName'
for row in table_data:
ws.append(row)
excel_file = io.BytesIO()
wb.save(excel_file)
excel_file.seek(0)
# Upload the Excel file to Azure Blob container using SAS Token
from azure.storage.blob import BlobServiceClient
# Get the SAS Token
sas_token = 'SAS_TOKEN'
# Create a BlobServiceClient object
blob_service_client = BlobServiceClient.from_connection_string('AZURE_STORAGE_CONNECTION_STRING')
# Get the BlobContainerClient object
blob_container_client = blob_service_client.get_container_client('CONTAINER_NAME')
# Upload the Excel file to the Blob container
blob_client = blob_container_client.get_blob_client('TableName.xlsx')
blob_client.upload_blob(excel_file, overwrite=True, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
# Close the cursor and connection
cursor.close()
cn.close()