This will generate a .exe file in the dist directory. Ensure the images (light.png, medium.png, dark.png) are in the same folder as this script.
"""
import tableauserverclient as TSC
import keyring
import pandas as pd
import os
import io
import time
import shutil
import platform
import datetime
import argparse
import tkinter as tk
from tkinter import filedialog, messagebox
import re # Ensure this is at the top of your file with other imports
import getpass
import uuid # Ensure this is at the top of your file with other imports
from openpyxl import load_workbook
from openpyxl.worksheet.table import Table, TableStyleInfo
from openpyxl.utils import get_column_letter
from openpyxl.styles import Font
import yaml
import ctypes
import threading
from PIL import Image, ImageTk
def get_tableau_connection(args):
token_value = keyring.get_password("TableauToken", args.token)
if not token_value:
raise Exception(f"Token '{args.token}' not found in keyring. Please use the 'Save Tableau Token' button to store it.")
def wait_until_1045_and_run_daily():
if args.now:
print("⏱ Running immediately due to --now argument")
download_all_views_to_excel(args)
return
code
print("⏳ Script is running. Will execute daily at 10:45 AM...")
while True:
now = datetime.datetime.now()
target_time = now.replace(hour=10, minute=45, second=0, microsecond=0)
if now >= target_time:
# If it's already past 10:45 AM today, schedule for the next day
target_time = target_time + datetime.timedelta(days=1)
wait_seconds = (target_time - now).total_seconds()
print(f"🕒 Waiting {int(wait_seconds)} seconds until next execution at {target_time.strftime('%Y-%m-%d %H:%M:%S')}...")
time.sleep(wait_seconds)
print(f"\n🕙 Running report for {datetime.datetime.now().strftime('%Y-%m-%d')}...")
try:
download_all_views_to_excel(args)
except Exception as e:
print(f"❌ Error during execution: {e}")
if name == "main":
launch_gui()
Assistant
Looking at your Python script, I can see it's a Tableau export tool with a GUI. Here's my review with suggested improvements:
Critical Issues
1. Missing Import
python
import sys # Add this - it's used but not imported
if os.path.exists(EXCEL_FILE_DEST):
print(f"⚠️ Excel file already exists: {EXCEL_FILE_DEST}")
return
server, auth = get_tableau_connection(args)
with server.auth.sign_in(auth):
print(f"\n🔐 Logged into Tableau as {USERNAME}")
# Find the workbook
workbooks = list(TSC.Pager(server.workbooks))
print(f"Looking for workbook named exactly: '{REPORT_NAME}'")
target_wb = next((wb for wb in workbooks if wb.name.lower() == REPORT_NAME.lower()), None)
if target_wb:
print(f"✅ Matched workbook: '{target_wb.name}' in project '{target_wb.project_name}'")
if not target_wb:
print(f"❌ Workbook '{REPORT_NAME}' not found.")
return
server.workbooks.populate_views(target_wb)
views = target_wb.views
if not views:
print("⚠️ No views found in workbook.")
return
if not os.path.exists(DOWNLOAD_FOLDER):
os.makedirs(DOWNLOAD_FOLDER)
excel_writer = pd.ExcelWriter(EXCEL_FILE, engine='openpyxl')
for view in views:
if stop_event.is_set():
print("🛑 Export cancelled by user.")
break
if view.name.strip().lower() in ("readme", "read me"):
print(f"ℹ️ Skipping view '{view.name}' (not intended for export)")
continue
server.views.populate_csv(view)
csv_data = b''.join(view.csv).decode('utf-8', errors='replace')
try:
df = pd.read_csv(
io.StringIO(csv_data),
engine="python",
encoding="utf-8",
sep=",",
quotechar='"',
escapechar="\\",
on_bad_lines="warn"
)
# Pivot Measure Names/Values into columns
if "Measure Names" in df.columns and "Measure Values" in df.columns:
# Drop rows where Measure Values are all NaN
df = df.dropna(subset=["Measure Values"])
# Convert to numeric if possible
df["Measure Values"] = pd.to_numeric(df["Measure Values"], errors="coerce")
# Try to heuristically choose index columns
possible_id_vars = [
col for col in df.columns
if col not in ["Measure Names", "Measure Values"]
and df[col].nunique() < len(df) * 0.5
and df[col].dtype == object
]
if not possible_id_vars:
possible_id_vars = [col for col in df.columns if col not in ["Measure Names", "Measure Values"]]
df = df.pivot_table(
index=possible_id_vars,
columns="Measure Names",
values="Measure Values",
aggfunc="first"
).reset_index()
df.columns.name = None # Flatten column headers
# Remove numeric prefixes like '01-', '02-' from headers
df.columns = df.columns.str.replace(r"^\d{2}-", "", regex=True)
# Remove non-printable characters to avoid Excel export errors (e.g., GD SZ HANâ␦␦S LASER TECH issue)
# Clean up any non-printable or problematic characters from all string cells
df = df.map(lambda x: ''.join(c for c in str(x) if c.isprintable()) if isinstance(x, str) else x)
sheet_name = sanitize_sheet_name(view.name)
try:
df.to_excel(excel_writer, sheet_name=sheet_name, index=False)
if "Amt - Net USD" in df.columns or "Qty - Net" in df.columns or "Revenue" in df.columns:
wb = excel_writer.book
ws = wb[sheet_name]
totals = []
for col in df.columns:
if col in ["Amt - Net USD", "Qty - Net", "Revenue"]:
col_sum = df[col].sum()
totals.append(col_sum)
else:
totals.append("")
ws.append(totals)
print(f"✅ View '{view.name}' added to Excel")
except Exception as e:
print(f"❌ Could not write view '{view.name}' to Excel sheet '{sheet_name}': {e}")
except Exception as e:
print(f"❌ Error processing view '{view.name}': {e}")
excel_writer.close()
time.sleep(0.5)
# === Add tables, freeze headers, style, and auto-fit ===
wb = load_workbook(EXCEL_FILE)
for sheet in wb.sheetnames:
ws = wb[sheet]
max_row = ws.max_row
max_col = ws.max_column
last_col_letter = get_column_letter(max_col)
# Add table with styling only if data exists
if max_row > 1 and max_col > 0:
table_range = f"A1:{last_col_letter}{max_row}"
safe_sheet = re.sub(r"[^\w]", "_", sheet)[:20]
table_name = f"Table_{safe_sheet}_{uuid.uuid4().hex[:6]}"
try:
tab = Table(displayName=table_name, ref=table_range)
style_name = f"TableStyle{args.table_weight}{get_color_code(args.table_color)}"
style = TableStyleInfo(name=style_name, showFirstColumn=False,
showLastColumn=False, showRowStripes=True, showColumnStripes=False)
tab.tableStyleInfo = style
ws.add_table(tab)
print(f"🧾 Table added to sheet '{sheet}' ({table_range})")
except Exception as e:
print(f"⚠️ Could not add table to sheet '{sheet}': {e}")
else:
print(f"ℹ️ Skipped adding table to sheet '{sheet}' (empty or invalid range)")
# Freeze header row
ws.freeze_panes = "A2"
# Set header row font to white and bold
for col in range(1, max_col + 1):
cell = ws.cell(row=1, column=col)
cell.font = Font(color="FFFFFF", bold=True)
# Auto-fit columns
for col in ws.columns:
max_length = 0
col_letter = get_column_letter(col[0].column)
for cell in col:
try:
cell_value = str(cell.value) if cell.value is not None else ""
max_length = max(max_length, len(cell_value))
except:
pass
adjusted_width = max_length + 2
ws.column_dimensions[col_letter].width = adjusted_width
wb.save(EXCEL_FILE)
print(f"📘 Excel workbook saved: {EXCEL_FILE}")
# === Archive old files (older than 5 days) ===
archive_folder = os.path.join(ONEDRIVE_DESTINATION, "Archive")
os.makedirs(archive_folder, exist_ok=True)
now = time.time()
cutoff = now - (args.archive_days * 86400) # archive_days in seconds
for filename in os.listdir(ONEDRIVE_DESTINATION):
if filename.startswith(FILENAME_SAFE_WB) and filename.endswith(".xlsx"):
file_path = os.path.join(ONEDRIVE_DESTINATION, filename)
if os.path.isfile(file_path) and os.path.getmtime(file_path) < cutoff:
try:
shutil.move(file_path, os.path.join(archive_folder, filename))
print(f"📦 Archived old file: {filename}")
except Exception as e:
print(f"⚠️ Failed to archive {filename}: {e}")
# === Move Excel to OneDrive ===
if os.path.exists(EXCEL_FILE):
os.makedirs(ONEDRIVE_DESTINATION, exist_ok=True)
shutil.move(EXCEL_FILE, EXCEL_FILE_DEST)
print(f"📁 Excel file moved to: {EXCEL_FILE_DEST}")
else:
print("❌ Excel file not found to move.")
success_message = "✅ All views processed, cleaned, formatted, exported, and archived successfully."
print(success_message)
try:
messagebox.showinfo("Success", success_message)
except:
pass
class TableauConnectionError(Exception):
"""Custom exception for Tableau connection issues"""
pass
def get_tableau_connection(config):
try:
token_value = keyring.get_password("TableauToken", config['token'])
if not token_value:
raise TableauConnectionError(
f"Token '{config['token']}' not found in keyring. "
"Please use the 'Save Tableau Token' button to store it."
)
tableau_auth = TSC.PersonalAccessTokenAuth(
config['token'],
token_value,
site_id=""
)
server = TSC.Server("https://tableau.microchip.com")
server.use_server_version()
return server, tableau_auth
except Exception as e:
raise TableauConnectionError(f"Failed to connect to Tableau: {str(e)}")
6. Context Managers for Resource Management
python
from contextlib import contextmanager
@contextmanager
def excel_writer_context(file_path):
writer = pd.ExcelWriter(file_path, engine='openpyxl')
try:
yield writer
writer.close()
except Exception as e:
writer.close()
if os.path.exists(file_path):
os.remove(file_path)
raise e
7. Improved DataFrame Processing
python
def process_dataframe(df):
"""Process and clean dataframe with better error handling"""
if df.empty:
return df
# Handle Measure Names/Values pivoting
if {"Measure Names", "Measure Values"}.issubset(df.columns):
df = pivot_measures(df)
# Clean column names
df.columns = df.columns.str.replace(r"^\d{2}-", "", regex=True)
# Clean string data
df = df.applymap(lambda x: clean_string(x) if isinstance(x, str) else x)
return df
def clean_string(text):
"""Remove non-printable characters from strings"""
return ''.join(c for c in text if c.isprintable())
def pivot_measures(df):
"""Pivot Measure Names/Values into columns"""
df = df.dropna(subset=["Measure Values"])
df["Measure Values"] = pd.to_numeric(df["Measure Values"], errors="coerce")
# Intelligent column selection for pivot
exclude_cols = {"Measure Names", "Measure Values"}
id_vars = [
col for col in df.columns
if col not in exclude_cols
and (df[col].nunique() < len(df) * 0.5 or df[col].dtype != object)
]
if not id_vars:
id_vars = [col for col in df.columns if col not in exclude_cols]
return df.pivot_table(
index=id_vars,
columns="Measure Names",
values="Measure Values",
aggfunc="first"
).reset_index()
8. Better Threading Implementation
python
class ExportThread(threading.Thread):
def __init__(self, exporter, callback=None):
super().__init__()
self.exporter = exporter
self.callback = callback
self.exception = None
def run(self):
try:
self.exporter.export()
if self.callback:
self.callback(success=True)
except Exception as e:
self.exception = e
if self.callback:
self.callback(success=False, error=str(e))
9. Configuration Validation
python
def validate_config(config):
"""Validate configuration before running export"""
required_fields = ['workbook', 'report', 'username', 'token', 'onedrive']
errors = []
for field in required_fields:
if not config.get(field):
errors.append(f"Missing required field: {field}")
if not os.path.exists(config.get('onedrive', '')):
errors.append(f"OneDrive path does not exist: {config.get('onedrive')}")
try:
archive_days = int(config.get('archive_days', 5))
if archive_days < 0:
errors.append("Archive days must be non-negative")
except ValueError:
errors.append("Archive days must be a number")
if errors:
raise ValueError("\n".join(errors))
10. Logging Instead of Print Statements
python
import logging
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
# Replace print statements with logging
logger.info("Logged into Tableau as %s", username)
logger.error("Workbook '%s' not found", report_name)
11. Better File Operations
python
def safe_file_move(source, destination):
"""Safely move file with proper error handling"""
try:
# Ensure destination directory exists
os.makedirs(os.path.dirname(destination), exist_ok=True)
# Check if destination already exists
if os.path.exists(destination):
backup = f"{destination}.backup_{int(time.time())}"
shutil.move(destination, backup)
logger.warning(f"Existing file backed up to: {backup}")
shutil.move(source, destination)
logger.info(f"File moved successfully to: {destination}")
except Exception as e:
logger.error(f"Failed to move file: {e}")
raise