Use run_shell with cd and heredoc syntax for complex Excel operations when read_file fails on XLSX or execute_code_sandbox fails on multi-step workbook creation
复制下面这句话,粘贴给 Claude Code、Codex、Cursor 等 AI 编程工具,它会读取安装说明并在你确认后完成安装。
请阅读 https://ai.atlankj.com/install/asset/gh-reliable-excel-workbook-creation-864f1c87ce61 ,按照其中的说明把「reliable-excel-workbook-creation」安装到你(当前 AI 工具)中。执行前先告诉我将运行的命令和写入的位置,等我确认。
查看 AI 将读取的安装说明正在读取 GitHub 原文…
内容来自 GitHub 原始文件,由原作者维护。在 GitHub 查看
Use this technique when you need to:
read_file cannot handle properlyexecute_code_sandbox on persistent file operationsAvoid: read_file for XLSX files, execute_code_sandbox for multi-step workbook creation
cd /workspace && python3 << 'EOF'
from openpyxl import Workbook
# Your Excel operations here
wb = Workbook()
# ... create sheets, add data, save
wb.save('/workspace/filename.xlsx')
EOF
Always start with cd /workspace && to ensure file paths resolve correctly.
Use << 'EOF' (single quotes) to prevent shell variable expansion within the Python code.
Include all imports, workbook creation, data population, and save operations in one script.
Always save with full path: /workspace/your_filename.xlsx
cd /workspace && python3 << 'EOF'
from openpyxl import Workbook
from openpyxl.styles import Font, Alignment, PatternFill
# Create workbook
wb = Workbook()
# Create multiple sheets
sheets = ['Summary', 'Data', 'Analysis', 'Settings']
for sheet_name in sheets:
wb.create_sheet(title=sheet_name)
# Remove default sheet if needed
if 'Sheet' in wb.sheetnames:
del wb['Sheet']
# Populate data
ws = wb['Data']
ws['A1'] = 'Item'
ws['B1'] = 'Value'
ws['A2'] = 'Revenue'
ws['B2'] = 100000
# Apply formatting
header_font = Font(bold=True)
for cell in ws['1:1']:
cell.font = header_font
# Save workbook
wb.save('/workspace/report.xlsx')
print('Workbook created successfully: /workspace/report.xlsx')
EOF
| Approach | Problem | Solution |
|---|---|---|
read_file | Cannot parse XLSX binary format | Don't use for Excel files |
execute_code_sandbox | File persistence issues, multi-step failures | Use run_shell instead |
run_shell with heredoc | ✓ Reliable, full control, persistent files | Use this pattern |
cd /workspace && python3 << 'EOF'
from openpyxl import Workbook
wb = Workbook()
sheet_names = ['Sheet1', 'Sheet2', 'Sheet3']
for name in sheet_names:
wb.create_sheet(title=name)
wb.save('/workspace/multi_sheet.xlsx')
EOF
cd /workspace && python3 << 'EOF'
from openpyxl import load_workbook
wb = load_workbook('/workspace/existing.xlsx')
ws = wb.active
ws['A1'] = 'Updated Value'
wb.save('/workspace/existing.xlsx')
EOF
cd /workspace && python3 << 'EOF'
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws['A1'] = 100
ws['A2'] = 200
ws['A3'] = '=SUM(A1:A2)'
wb.save('/workspace/with_formulas.xlsx')
EOF
/workspace/ prefix in all paths'EOF' to prevent shell interpretation/workspace/filename.xlsx)<< 'EOF') prevents variable expansion