Create Excel files with openpyxl by falling back to shell-based Python heredoc when sandbox execution fails
When creating Excel files with openpyxl, execute_code_sandbox may fail due to sandbox restrictions, missing dependencies, or permission issues. This skill provides a reliable fallback: execute Python code via run_shell using an inline heredoc script. This approach often succeeds where the sandbox fails and supports full openpyxl features including styling, formulas, and formatting.
execute_code_sandbox fails when importing or using openpyxlAlways try execute_code_sandbox first, as it's cleaner and preferred when it works:
from openpyxl import Workbook
from openpyxl.styles import Font, Fill, PatternFill, Alignment
wb = Workbook()
ws = wb.active
ws['A1'] = 'Header'
ws['A1'].font = Font(bold=True)
wb.save('output.xlsx')
Watch for these failure indicators:
When sandbox fails, switch to run_shell with a Python heredoc:
python3 << 'EOF'
from openpyxl import Workbook
from openpyxl.styles import Font, Fill, PatternFill, Alignment, Border, Side
# Create workbook
wb = Workbook()
ws = wb.active
ws.title = "Sheet1"
# Add data with formatting
ws['A1'] = 'Name'
ws['B1'] = 'Value'
ws['A1'].font = Font(bold=True, size=14)
ws['B1'].font = Font(bold=True, size=14)
# Add rows
data = [
['Item 1', 100],
['Item 2', 200],
['Item 3', 150],
]
for row_idx, row_data in enumerate(data, start=2):
for col_idx, value in enumerate(row_data, start=1):
cell = ws.cell(row=row_idx, column=col_idx, value=value)
cell.alignment = Alignment(horizontal='center')
# Add formulas if needed
ws['B5'] = '=SUM(B2:B4)'
# Save the file
wb.save('output.xlsx')
print("Excel file created successfully: output.xlsx")
EOF
Execute the heredoc via run_shell: