Skip to main content

Database Query to Email Report

Connect to database, run a query, export to Excel, and email the report

Steps

#ActivityWhat it does
1OpenDatabaseConnectionConnect to the database
2RunQueryExecute report query
3CreateTableCreate an in-memory table for the query rows
4ForEachLoopPush each query row into the table
5TableUpsertRowAppend the row to the table
6TableExportExport the rows to Excel
7SMTPEmailEmail the report
8CloseDatabaseConnectionClose the connection

Workflow

dbConn = OpenDatabaseConnection(connectionString="postgresql://user:pass@localhost:5432/mydb", databaseType="postgres")
queryResults = RunQuery(dbConn, "SELECT * FROM sales WHERE date >= CURRENT_DATE - INTERVAL '7 days'")
CreateTable("salesReport", schema={"columns": [{"name": "date"}, {"name": "amount"}, {"name": "customer"}]})
for row in queryResults:
TableUpsertRow("salesReport", {"date": "{{ row.date }}", "amount": "{{ row.amount }}", "customer": "{{ row.customer }}"}, append=True)
TableExport("salesReport", "./weekly_report.xlsx", format="xlsx", sheetName="Sales")
SMTPEmail("manager@example.com", emailBody="{{ 'Weekly report attached with ' + queryResults.length + ' records.' }}", emailSubject="Weekly Sales Report")
CloseDatabaseConnection(dbConn)