Use run_shell with inline Python as a fallback when execute_code_sandbox fails for openpyxl/spreadsheet operations
复制下面这句话,粘贴给 Claude Code、Codex、Cursor 等 AI 编程工具,它会读取安装说明并在你确认后完成安装。
请阅读 https://ai.atlankj.com/install/asset/gh-openpyxl-sandbox-workaround-42a05a6faec9 ,按照其中的说明把「openpyxl-sandbox-workaround」安装到你(当前 AI 工具)中。执行前先告诉我将运行的命令和写入的位置,等我确认。
查看 AI 将读取的安装说明正在读取 GitHub 原文…
内容来自 GitHub 原始文件,由原作者维护。在 GitHub 查看
Use this pattern when execute_code_sandbox repeatedly fails for openpyxl or spreadsheet manipulation tasks. The sandbox environment may have compatibility issues with certain openpyxl operations, but running Python directly via run_shell often succeeds.
execute_code_sandbox returns errors related to openpyxl imports or operationsInstead of using execute_code_sandbox, use run_shell with an inline Python script:
python3 << 'EOF'
from openpyxl import Workbook
from openpyxl.utils import get_column_letter
# Your openpyxl code here
wb = Workbook()
ws = wb.active
ws.title = "Sheet1"
# Add data
ws['A1'] = 'Header'
ws['B1'] = 'Value'
# Save file
wb.save('output.xlsx')
print('File created successfully')
EOF
For complex operations involving multiple files or data processing:
python3 << 'EOF'
from openpyxl import Workbook, load_workbook
import os
# Load existing workbook if needed
if os.path.exists('input.xlsx'):
wb = load_workbook('input.xlsx')
ws = wb.active
# Process data...
# Create new workbook
wb = Workbook()
ws = wb.active
# Add data with proper formatting
for row_idx, row_data in enumerate(data, start=1):
for col_idx, value in enumerate(row_data, start=1):
ws.cell(row=row_idx, column=col_idx, value=value)
# Auto-adjust column widths
for column in ws.columns:
max_length = 0
column_letter = get_column_letter(column[0].column)
for cell in column:
try:
if len(str(cell.value)) > max_length:
max_length = len(str(cell.value))
except:
pass
adjusted_width = min(max_length + 2, 50)
ws.column_dimensions[column_letter].width = adjusted_width
wb.save('output.xlsx')
EOF
<< 'EOF' pattern prevents variable expansion issuesAfter running the script, verify the file was created:
ls -la *.xlsx
Or check file details:
python3 << 'EOF'
from openpyxl import load_workbook
wb = load_workbook('output.xlsx')
print(f"Sheets: {wb.sheetnames}")
print(f"Active sheet: {wb.active.title}")
EOF
execute_code_sandbox attempt fails with openpyxl errors