[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6HX2R0MC13R5G3S8N2H0V0J":3,"skill-same:01M6HX2R0MC13R5G3S8N2H0V0J":73},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":26,"publishedAt":40,"linkOnly":41,"markdownContent":42,"markdownBody":43,"frontMatter":44,"refName":45,"commitSha":46,"skillDirectory":47,"forksCount":48,"repositoryHtmlUrl":49,"repositoryHomepageUrl":6,"ownerHtmlUrl":50,"ownerBlogUrl":51,"ownerDescription":6,"updatedAt":52,"install":53,"resources":66},"01M6HX2R0MC13R5G3S8N2H0V0J","document-python-direct-exec",null,"Use direct Python execution for reliable spreadsheet and document\u002FPDF generation operations","HKUDS\u002FAgentPilot","HKUDS","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F118165258?v=4","01M6HW8VRNZP64G0P4MVJW2KKQ","✨Data Intelligence Lab@HKU✨","01M6HW8VWZVHBRHYH3T330PFWV",8029,"MIT","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Fbenchmarks\u002Fgdpval\u002Fskills\u002Fspreadsheet-direct-python-merged-343937\u002FSKILL.md",[18,23],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000002","文档处理","SCENARIO","使用场景",{"categoryNo":24,"categoryName":25,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000004","电子表格",[27,28,29,30,31,32,33,34,35,36,37,38,39],"python","direct","document","exec","document python direct exec","PDF","execution","spreadsheet","operations","use","generation","pdf generation","for","2026-11-10 10:12:30",false,"---\nname: document-python-direct-exec\ndescription: Use direct Python execution for reliable spreadsheet and document\u002FPDF generation operations\n---\n\n# Direct Python Execution for Spreadsheet and Document Tasks\n\n## When to Use This Skill\n\nUse direct `run_shell` with Python scripts for structured document operations when:\n\n- **Spreadsheets**: Reading or writing complex Excel files with multiple sheets, applying formulas, formatting, or data transformations\n- **PDFs**: Generating PDF checklists, reports, invoices, or forms with precise layout control\n- **Documents**: Creating Word documents, HTML reports, or other structured output formats\n- **Complex Operations**: The task involves multiple steps that could exceed agent step limits\n- **Precision Needed**: You need precise control over error handling, debugging, and library imports\n\n## Why Direct Execution?\n\nThe `shell_agent` tool can:\n\n- Hit maximum step limits on complex multi-step operations\n- Produce unexplained errors on formatting operations\n- Fail on intricate reads\u002Fwrites due to iterative parsing\n- Fail to parse heredoc syntax correctly, causing 'unknown error' failures\n\nDirect `run_shell` with Python is more reliable because it:\n\n- Executes in a single step with no iteration limits\n- Provides clearer, immediate error messages\n- Handles complex operations without step constraints\n- Gives full control over library imports and execution flow\n- Writing scripts to `.py` files first avoids shell_agent parsing issues with heredocs\n\n## How to Use\n\n### Recommended Pattern: Write Script to File First\n\nFor complex multi-line scripts, especially when using shell_agent as executor:\n\n```bash\n# Step 1: Write the Python script to a file\ncat > process_document.py \u003C\u003C 'EOF'\n# Your document\u002Fspreadsheet code here\nEOF\n\n# Step 2: Execute the script\npython3 process_document.py\n```\n\n### Alternative Pattern: Inline Heredoc (Simple Scripts Only)\n\nFor short, simple scripts when NOT using shell_agent as the executor:\n\n```bash\npython3 \u003C\u003C 'EOF'\n# Your code here\nEOF\n```\n\n## Spreadsheet Examples\n\n### Example 1: Read and Transform Excel Data\n\n```python\nimport pandas as pd\n\n# Load data from specific sheet\ndf = pd.read_excel('input.xlsx', sheet_name='Revenue')\n\n# Apply transformations\ndf['Net_Revenue'] = df['Gross_Revenue'] * (1 - df['Tax_Rate'])\n\n# Save results\ndf.to_excel('output.xlsx', index=False, sheet_name='Processed')\n```\n\n### Example 2: Multi-Sheet Operations with openpyxl\n\n```python\nfrom openpyxl import load_workbook\n\nwb = load_workbook('tour_data.xlsx')\n\n# Iterate through sheets\nfor sheet_name in wb.sheetnames:\n    ws = wb[sheet_name]\n    # Apply formatting or calculations\n    for row in ws.iter_rows(min_row=2, max_col=5):\n        # Process cells\n        pass\n\nwb.save('tour_data_processed.xlsx')\n```\n\n### Example 3: Complex Formatting Operations\n\n```python\nfrom openpyxl import load_workbook\nfrom openpyxl.styles import Font, PatternFill, Alignment\n\nwb = load_workbook('report.xlsx')\nws = wb.active\n\n# Apply header styling\nheader_fill = PatternFill(start_color='4472C4', fill_type='solid')\nheader_font = Font(bold=True, color='FFFFFF')\n\nfor cell in ws[1]:\n    cell.fill = header_fill\n    cell.font = header_font\n    cell.alignment = Alignment(horizontal='center')\n\nwb.save('report_formatted.xlsx')\n```\n\n## PDF Generation Examples\n\n### Example 4: Generate PDF Checklist with ReportLab\n\n```python\nfrom reportlab.lib.pagesizes import letter\nfrom reportlab.pdfgen import canvas\nfrom reportlab.lib.units import inch\n\ndef create_checklist(pdf_path, items):\n    c = canvas.Canvas(pdf_path, pagesize=letter)\n    width, height = letter\n    \n    # Title\n    c.setFont(\"Helvetica-Bold\", 16)\n    c.drawString(1*inch, height - 1*inch, \"Safety Checklist\")\n    \n    # Checklist items\n    c.setFont(\"Helvetica\", 12)\n    y_position = height - 1.5*inch\n    \n    for i, item in enumerate(items, 1):\n        checkbox_x = 1*inch\n        text_x = 1.3*inch\n        c.drawString(checkbox_x, y_position, \"☐\")  # Empty checkbox\n        c.drawString(text_x, y_position, f\"{i}. {item}\")\n        y_position -= 0.3*inch\n        \n        # New page if needed\n        if y_position \u003C 1*inch:\n            c.showPage()\n            y_position = height - 1*inch\n    \n    c.save()\n    print(f\"Created checklist: {pdf_path}\")\n\n# Usage\nitems = [\n    \"Verify equipment is powered off\",\n    \"Check safety gear is available\",\n    \"Inspect work area for hazards\",\n    \"Confirm emergency contacts are posted\"\n]\ncreate_checklist('safety_checklist.pdf', items)\n```\n\n### Example 5: Generate PDF Report with Tables\n\n```python\nfrom reportlab.lib import colors\nfrom reportlab.lib.pagesizes import letter\nfrom reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph, Spacer\nfrom reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle\nfrom reportlab.lib.units import inch\n\ndef create_report(pdf_path, title, data, column_headers):\n    doc = SimpleDocTemplate(pdf_path, pagesize=letter,\n                           rightMargin=0.75*inch, leftMargin=0.75*inch,\n                           topMargin=0.75*inch, bottomMargin=0.75*inch)\n    \n    elements = []\n    styles = getSampleStyleSheet()\n    \n    # Title\n    title_style = ParagraphStyle('CustomTitle', parent=styles['Heading1'],\n                                 fontSize=18, spaceAfter=30, alignment=1)\n    elements.append(Paragraph(title, title_style))\n    elements.append(Spacer(1, 0.25*inch))\n    \n    # Table\n    table_data = [column_headers] + data\n    table = Table(table_data, colWidths=[2*inch, 1.5*inch, 1.5*inch])\n    \n    # Table styling\n    table.setStyle(TableStyle([\n        ('BACKGROUND', (0, 0), (-1, 0), colors.HexColor('#4472C4')),\n        ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),\n        ('ALIGN', (0, 0), (-1, -1), 'CENTER'),\n        ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),\n        ('FONTSIZE', (0, 0), (-1, 0), 12),\n        ('BOTTOMPADDING', (0, 0), (-1, 0), 12),\n        ('ROWBACKGROUNDS', (0, 1), (-1, -1), [colors.white, colors.HexColor('#D6DCE4')]),\n        ('GRID', (0, 0), (-1, -1), 0.5, colors.grey),\n    ]))\n    \n    elements.append(table)\n    doc.build(elements)\n    print(f\"Created report: {pdf_path}\")\n\n# Usage\nheaders = ['Item', 'Quantity', 'Status']\ndata = [\n    ['Widget A', '150', 'Complete'],\n    ['Widget B', '200', 'In Progress'],\n    ['Widget C', '75', 'Pending']\n]\ncreate_report('status_report.pdf', 'Weekly Status Report', data, headers)\n```\n\n### Example 6: PDF with Images and Text (FPDF Alternative)\n\n```python\nfrom fpdf import FPDF\n\nclass PDF(FPDF):\n    def header(self):\n        self.set_font('Arial', 'B', 15)\n        self.cell(0, 10, 'Project Documentation', 0, 1, 'C')\n        self.ln(10)\n    \n    def footer(self):\n        self.set_y(-15)\n        self.set_font('Arial', 'I', 8)\n        self.cell(0, 10, f'Page {self.page_no()}', 0, 0, 'C')\n\ndef create_document(pdf_path, title, sections):\n    pdf = PDF()\n    pdf.add_page()\n    pdf.set_font('Arial', 'B', 16)\n    pdf.cell(0, 10, title, 0, 1, 'L')\n    pdf.ln(5)\n    \n    pdf.set_font('Arial', '', 12)\n    for section in sections:\n        pdf.set_font('Arial', 'B', 14)\n        pdf.cell(0, 10, section['title'], 0, 1)\n        pdf.set_font('Arial', '', 12)\n        pdf.multi_cell(0, 6, section['content'])\n        pdf.ln(5)\n    \n    pdf.output(pdf_path)\n    print(f\"Created document: {pdf_path}\")\n\n# Usage\nsections = [\n    {'title': 'Overview', 'content': 'This document provides...'},\n    {'title': 'Requirements', 'content': 'The following requirements...'},\n    {'title': 'Timeline', 'content': 'Project phases are...'}\n]\ncreate_document('project_doc.pdf', 'Project Alpha', sections)\n```\n\n## Error Handling Pattern\n\n```python\nimport sys\nfrom reportlab.lib.pagesizes import letter\nfrom reportlab.pdfgen import canvas\n\ntry:\n    c = canvas.Canvas('output.pdf', pagesize=letter)\n    \n    # Your document operations here\n    c.drawString(100, 750, \"Document content\")\n    \n    c.save()\n    print(\"Success: PDF created\")\n    \nexcept Exception as e:\n    print(f\"Error: {str(e)}\", file=sys.stderr)\n    sys.exit(1)\n```\n\n## Best Practices\n\n1. **Prefer file-based execution** for complex scripts: write to `.py` file first, then execute via `run_shell`\n2. **Import only needed libraries** to reduce execution time and avoid dependency conflicts\n3. **Print clear success\u002Ferror messages** for debugging\n4. **Save intermediate results** for complex multi-step transformations\n5. **Test with small data** before scaling to large documents or spreadsheets\n6. **Use appropriate libraries for the task**: pandas\u002Fopenpyxl for spreadsheets, reportlab\u002Ffpdf for PDFs\n7. **Clean up temporary script files** after execution if they won't be reused\n8. **Use absolute paths or verify working directory** to avoid file not found errors\n9. **For PDFs**: Build content in memory first, then write to file atomically\n\n## When NOT to Use This Skill\n\n- Simple single-cell reads\u002Fwrites (use shell_agent or basic commands)\n- Operations that require interactive user input\n- Tasks where you need the agent to iteratively refine the approach\n- When the target format has a simpler CLI tool available (e.g., `pandoc` for document conversion)\n\n## Common Libraries\n\n| Library | Best For |\n|---------|----------|\n| `openpyxl` | Reading\u002Fwriting .xlsx files, formatting, formulas |\n| `pandas` | Data manipulation, analysis, merging datasets |\n| `xlrd` | Reading older .xls files (read-only) |\n| `xlsxwriter` | Creating new .xlsx files with advanced formatting |\n| `reportlab` | Professional PDF generation with precise layout control |\n| `fpdf` | Simple PDF creation, easier learning curve |\n| `python-docx` | Creating and editing Word documents |\n| `weasyprint` | HTML\u002FCSS to PDF conversion |\n\n## Troubleshooting\n\n**Issue**: Heredoc syntax fails with 'unknown error' when using shell_agent\n- **Solution**: Write the Python script to a `.py` file first, then execute it with `python3 script.py`. This pattern is significantly more reliable than inline heredoc execution when shell_agent is the executor.\n\n**Issue**: FileNotFoundError\n- **Solution**: Verify the file path is absolute or relative to the working directory. Use `os.getcwd()` to confirm current directory if needed.\n\n**Issue**: PermissionError\n- **Solution**: Ensure the file is not open in another application. On Linux\u002FMac, check file permissions with `ls -la`.\n\n**Issue**: ModuleNotFoundError\n- **Solution**: Install required libraries first: `pip install reportlab openpyxl pandas`. Some environments may need `pip3` instead.\n\n**Issue**: MemoryError on large files\n- **Solution**: Process data in chunks using pandas `chunksize` parameter. For PDFs, create multi-page documents instead of single massive pages.\n\n**Issue**: Formatting not applying (spreadsheets)\n- **Solution**: Ensure you're modifying cell styles before saving, and use `.copy()` for style objects to avoid reference issues.\n\n**Issue**: PDF text rendering incorrectly\n- **Solution**: Check font encoding. For special characters, use Unicode-compatible fonts or escape special characters. ReportLab supports UTF-8 with proper font configuration.\n\n**Issue**: PDF layout breaks across pages\n- **Solution**: Use ReportLab's flowable elements (Paragraph, Spacer) which handle page breaks automatically, or manually check y-position and call `showPage()` when needed.\n\n## Quick Reference: PDF vs Spreadsheet Choice\n\n| Need | Recommended Library |\n|------|---------------------|\n| Data analysis, calculations | `pandas` + Excel output |\n| Complex cell formatting | `openpyxl` |\n| Professional reports with tables | `reportlab` (PDF) |\n| Simple checklists, forms | `fpdf` or `reportlab` |\n| Word document output | `python-docx` |\n| HTML to PDF | `weasyprint` |\n| Both data + formatted output | Generate data with pandas, format with reportlab |\n","# Direct Python Execution for Spreadsheet and Document Tasks\n\n## When to Use This Skill\n\nUse direct `run_shell` with Python scripts for structured document operations when:\n\n- **Spreadsheets**: Reading or writing complex Excel files with multiple sheets, applying formulas, formatting, or data transformations\n- **PDFs**: Generating PDF checklists, reports, invoices, or forms with precise layout control\n- **Documents**: Creating Word documents, HTML reports, or other structured output formats\n- **Complex Operations**: The task involves multiple steps that could exceed agent step limits\n- **Precision Needed**: You need precise control over error handling, debugging, and library imports\n\n## Why Direct Execution?\n\nThe `shell_agent` tool can:\n\n- Hit maximum step limits on complex multi-step operations\n- Produce unexplained errors on formatting operations\n- Fail on intricate reads\u002Fwrites due to iterative parsing\n- Fail to parse heredoc syntax correctly, causing 'unknown error' failures\n\nDirect `run_shell` with Python is more reliable because it:\n\n- Executes in a single step with no iteration limits\n- Provides clearer, immediate error messages\n- Handles complex operations without step constraints\n- Gives full control over library imports and execution flow\n- Writing scripts to `.py` files first avoids shell_agent parsing issues with heredocs\n\n## How to Use\n\n### Recommended Pattern: Write Script to File First\n\nFor complex multi-line scripts, especially when using shell_agent as executor:\n\n```bash\n# Step 1: Write the Python script to a file\ncat > process_document.py \u003C\u003C 'EOF'\n# Your document\u002Fspreadsheet code here\nEOF\n\n# Step 2: Execute the script\npython3 process_document.py\n```\n\n### Alternative Pattern: Inline Heredoc (Simple Scripts Only)\n\nFor short, simple scripts when NOT using shell_agent as the executor:\n\n```bash\npython3 \u003C\u003C 'EOF'\n# Your code here\nEOF\n```\n\n## Spreadsheet Examples\n\n### Example 1: Read and Transform Excel Data\n\n```python\nimport pandas as pd\n\n# Load data from specific sheet\ndf = pd.read_excel('input.xlsx', sheet_name='Revenue')\n\n# Apply transformations\ndf['Net_Revenue'] = df['Gross_Revenue'] * (1 - df['Tax_Rate'])\n\n# Save results\ndf.to_excel('output.xlsx', index=False, sheet_name='Processed')\n```\n\n### Example 2: Multi-Sheet Operations with openpyxl\n\n```python\nfrom openpyxl import load_workbook\n\nwb = load_workbook('tour_data.xlsx')\n\n# Iterate through sheets\nfor sheet_name in wb.sheetnames:\n    ws = wb[sheet_name]\n    # Apply formatting or calculations\n    for row in ws.iter_rows(min_row=2, max_col=5):\n        # Process cells\n        pass\n\nwb.save('tour_data_processed.xlsx')\n```\n\n### Example 3: Complex Formatting Operations\n\n```python\nfrom openpyxl import load_workbook\nfrom openpyxl.styles import Font, PatternFill, Alignment\n\nwb = load_workbook('report.xlsx')\nws = wb.active\n\n# Apply header styling\nheader_fill = PatternFill(start_color='4472C4', fill_type='solid')\nheader_font = Font(bold=True, color='FFFFFF')\n\nfor cell in ws[1]:\n    cell.fill = header_fill\n    cell.font = header_font\n    cell.alignment = Alignment(horizontal='center')\n\nwb.save('report_formatted.xlsx')\n```\n\n## PDF Generation Examples\n\n### Example 4: Generate PDF Checklist with ReportLab\n\n```python\nfrom reportlab.lib.pagesizes import letter\nfrom reportlab.pdfgen import canvas\nfrom reportlab.lib.units import inch\n\ndef create_checklist(pdf_path, items):\n    c = canvas.Canvas(pdf_path, pagesize=letter)\n    width, height = letter\n    \n    # Title\n    c.setFont(\"Helvetica-Bold\", 16)\n    c.drawString(1*inch, height - 1*inch, \"Safety Checklist\")\n    \n    # Checklist items\n    c.setFont(\"Helvetica\", 12)\n    y_position = height - 1.5*inch\n    \n    for i, item in enumerate(items, 1):\n        checkbox_x = 1*inch\n        text_x = 1.3*inch\n        c.drawString(checkbox_x, y_position, \"☐\")  # Empty checkbox\n        c.drawString(text_x, y_position, f\"{i}. {item}\")\n        y_position -= 0.3*inch\n        \n        # New page if needed\n        if y_position \u003C 1*inch:\n            c.showPage()\n            y_position = height - 1*inch\n    \n    c.save()\n    print(f\"Created checklist: {pdf_path}\")\n\n# Usage\nitems = [\n    \"Verify equipment is powered off\",\n    \"Check safety gear is available\",\n    \"Inspect work area for hazards\",\n    \"Confirm emergency contacts are posted\"\n]\ncreate_checklist('safety_checklist.pdf', items)\n```\n\n### Example 5: Generate PDF Report with Tables\n\n```python\nfrom reportlab.lib import colors\nfrom reportlab.lib.pagesizes import letter\nfrom reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph, Spacer\nfrom reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle\nfrom reportlab.lib.units import inch\n\ndef create_report(pdf_path, title, data, column_headers):\n    doc = SimpleDocTemplate(pdf_path, pagesize=letter,\n                           rightMargin=0.75*inch, leftMargin=0.75*inch,\n                           topMargin=0.75*inch, bottomMargin=0.75*inch)\n    \n    elements = []\n    styles = getSampleStyleSheet()\n    \n    # Title\n    title_style = ParagraphStyle('CustomTitle', parent=styles['Heading1'],\n                                 fontSize=18, spaceAfter=30, alignment=1)\n    elements.append(Paragraph(title, title_style))\n    elements.append(Spacer(1, 0.25*inch))\n    \n    # Table\n    table_data = [column_headers] + data\n    table = Table(table_data, colWidths=[2*inch, 1.5*inch, 1.5*inch])\n    \n    # Table styling\n    table.setStyle(TableStyle([\n        ('BACKGROUND', (0, 0), (-1, 0), colors.HexColor('#4472C4')),\n        ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),\n        ('ALIGN', (0, 0), (-1, -1), 'CENTER'),\n        ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),\n        ('FONTSIZE', (0, 0), (-1, 0), 12),\n        ('BOTTOMPADDING', (0, 0), (-1, 0), 12),\n        ('ROWBACKGROUNDS', (0, 1), (-1, -1), [colors.white, colors.HexColor('#D6DCE4')]),\n        ('GRID', (0, 0), (-1, -1), 0.5, colors.grey),\n    ]))\n    \n    elements.append(table)\n    doc.build(elements)\n    print(f\"Created report: {pdf_path}\")\n\n# Usage\nheaders = ['Item', 'Quantity', 'Status']\ndata = [\n    ['Widget A', '150', 'Complete'],\n    ['Widget B', '200', 'In Progress'],\n    ['Widget C', '75', 'Pending']\n]\ncreate_report('status_report.pdf', 'Weekly Status Report', data, headers)\n```\n\n### Example 6: PDF with Images and Text (FPDF Alternative)\n\n```python\nfrom fpdf import FPDF\n\nclass PDF(FPDF):\n    def header(self):\n        self.set_font('Arial', 'B', 15)\n        self.cell(0, 10, 'Project Documentation', 0, 1, 'C')\n        self.ln(10)\n    \n    def footer(self):\n        self.set_y(-15)\n        self.set_font('Arial', 'I', 8)\n        self.cell(0, 10, f'Page {self.page_no()}', 0, 0, 'C')\n\ndef create_document(pdf_path, title, sections):\n    pdf = PDF()\n    pdf.add_page()\n    pdf.set_font('Arial', 'B', 16)\n    pdf.cell(0, 10, title, 0, 1, 'L')\n    pdf.ln(5)\n    \n    pdf.set_font('Arial', '', 12)\n    for section in sections:\n        pdf.set_font('Arial', 'B', 14)\n        pdf.cell(0, 10, section['title'], 0, 1)\n        pdf.set_font('Arial', '', 12)\n        pdf.multi_cell(0, 6, section['content'])\n        pdf.ln(5)\n    \n    pdf.output(pdf_path)\n    print(f\"Created document: {pdf_path}\")\n\n# Usage\nsections = [\n    {'title': 'Overview', 'content': 'This document provides...'},\n    {'title': 'Requirements', 'content': 'The following requirements...'},\n    {'title': 'Timeline', 'content': 'Project phases are...'}\n]\ncreate_document('project_doc.pdf', 'Project Alpha', sections)\n```\n\n## Error Handling Pattern\n\n```python\nimport sys\nfrom reportlab.lib.pagesizes import letter\nfrom reportlab.pdfgen import canvas\n\ntry:\n    c = canvas.Canvas('output.pdf', pagesize=letter)\n    \n    # Your document operations here\n    c.drawString(100, 750, \"Document content\")\n    \n    c.save()\n    print(\"Success: PDF created\")\n    \nexcept Exception as e:\n    print(f\"Error: {str(e)}\", file=sys.stderr)\n    sys.exit(1)\n```\n\n## Best Practices\n\n1. **Prefer file-based execution** for complex scripts: write to `.py` file first, then execute via `run_shell`\n2. **Import only needed libraries** to reduce execution time and avoid dependency conflicts\n3. **Print clear success\u002Ferror messages** for debugging\n4. **Save intermediate results** for complex multi-step transformations\n5. **Test with small data** before scaling to large documents or spreadsheets\n6. **Use appropriate libraries for the task**: pandas\u002Fopenpyxl for spreadsheets, reportlab\u002Ffpdf for PDFs\n7. **Clean up temporary script files** after execution if they won't be reused\n8. **Use absolute paths or verify working directory** to avoid file not found errors\n9. **For PDFs**: Build content in memory first, then write to file atomically\n\n## When NOT to Use This Skill\n\n- Simple single-cell reads\u002Fwrites (use shell_agent or basic commands)\n- Operations that require interactive user input\n- Tasks where you need the agent to iteratively refine the approach\n- When the target format has a simpler CLI tool available (e.g., `pandoc` for document conversion)\n\n## Common Libraries\n\n| Library | Best For |\n|---------|----------|\n| `openpyxl` | Reading\u002Fwriting .xlsx files, formatting, formulas |\n| `pandas` | Data manipulation, analysis, merging datasets |\n| `xlrd` | Reading older .xls files (read-only) |\n| `xlsxwriter` | Creating new .xlsx files with advanced formatting |\n| `reportlab` | Professional PDF generation with precise layout control |\n| `fpdf` | Simple PDF creation, easier learning curve |\n| `python-docx` | Creating and editing Word documents |\n| `weasyprint` | HTML\u002FCSS to PDF conversion |\n\n## Troubleshooting\n\n**Issue**: Heredoc syntax fails with 'unknown error' when using shell_agent\n- **Solution**: Write the Python script to a `.py` file first, then execute it with `python3 script.py`. This pattern is significantly more reliable than inline heredoc execution when shell_agent is the executor.\n\n**Issue**: FileNotFoundError\n- **Solution**: Verify the file path is absolute or relative to the working directory. Use `os.getcwd()` to confirm current directory if needed.\n\n**Issue**: PermissionError\n- **Solution**: Ensure the file is not open in another application. On Linux\u002FMac, check file permissions with `ls -la`.\n\n**Issue**: ModuleNotFoundError\n- **Solution**: Install required libraries first: `pip install reportlab openpyxl pandas`. Some environments may need `pip3` instead.\n\n**Issue**: MemoryError on large files\n- **Solution**: Process data in chunks using pandas `chunksize` parameter. For PDFs, create multi-page documents instead of single massive pages.\n\n**Issue**: Formatting not applying (spreadsheets)\n- **Solution**: Ensure you're modifying cell styles before saving, and use `.copy()` for style objects to avoid reference issues.\n\n**Issue**: PDF text rendering incorrectly\n- **Solution**: Check font encoding. For special characters, use Unicode-compatible fonts or escape special characters. ReportLab supports UTF-8 with proper font configuration.\n\n**Issue**: PDF layout breaks across pages\n- **Solution**: Use ReportLab's flowable elements (Paragraph, Spacer) which handle page breaks automatically, or manually check y-position and call `showPage()` when needed.\n\n## Quick Reference: PDF vs Spreadsheet Choice\n\n| Need | Recommended Library |\n|------|---------------------|\n| Data analysis, calculations | `pandas` + Excel output |\n| Complex cell formatting | `openpyxl` |\n| Professional reports with tables | `reportlab` (PDF) |\n| Simple checklists, forms | `fpdf` or `reportlab` |\n| Word document output | `python-docx` |\n| HTML to PDF | `weasyprint` |\n| Both data + formatted output | Generate data with pandas, format with reportlab |\n",{"name":5,"description":7},"main","6b84b0689ca0d9e7b1e4061188ff6b60758e0f8a","openspace\u002Fbenchmarks\u002Fgdpval\u002Fskills\u002Fspreadsheet-direct-python-merged-343937",944,"https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot","https:\u002F\u002Fgithub.com\u002FHKUDS","https:\u002F\u002Fsites.google.com\u002Fview\u002Fchaoh","2026-11-12 22:26:39",{"source":8,"skillName":5,"commands":54,"prompt":64,"zipAvailable":65},[55,58,61],{"tool":56,"command":57},"npx","npx skills add HKUDS\u002FAgentPilot --skill document-python-direct-exec",{"tool":59,"command":60},"bunx","bunx skills add HKUDS\u002FAgentPilot --skill document-python-direct-exec",{"tool":62,"command":63},"pnpm","pnpm dlx skills add HKUDS\u002FAgentPilot --skill document-python-direct-exec","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Fbenchmarks\u002Fgdpval\u002Fskills\u002Fspreadsheet-direct-python-merged-343937\u002FSKILL.md",true,[67],{"path":68,"resourceType":69,"resourceTypeDesc":70,"sizeBytes":71,"sourceHtmlUrl":72},".skill_id","OTHER","其他",53,"https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Fbenchmarks\u002Fgdpval\u002Fskills\u002Fspreadsheet-direct-python-merged-343937\u002F.skill_id",[74,93,112,135,158,180],{"skillNo":75,"name":76,"nameZh":6,"description":77,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":78,"categories":79,"keywords":80,"publishedAt":40},"01M6HYB297NDABRERJRVG0K8R0","agentpilot","Set up AgentPilot and use its single entry to prepare missing inputs and run configured RSI experiments. Use when the user requests AgentPilot installation or work with AgentPilot.","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fplugins\u002Fagentpilot\u002Fskills\u002Fagentpilot\u002FSKILL.md",[],[76,81,82,83,84,85,86,87,36,88,89,90,91,92],"prepare","requests","with","missing","installation","rsi","up","user","work","SET","run","experiments",{"skillNo":94,"name":95,"nameZh":6,"description":96,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":97,"categories":98,"keywords":99,"publishedAt":40},"01M6HYAYWXTTE1J7DJM0MFNQ4H","remember","Review auto-memory entries and propose promotions to OPENSPACE.md, OPENSPACE.local.md, or retained auto-memory topics; detect duplicates, stale facts, conflicts, and ambiguous entries before making changes.","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Fopenspace\u002Fskills\u002Fremember\u002FSKILL.md",[],[95,100,101,102,103,104,105,106,107,108,109,110,111],"memory","review","auto","openspace","changes","facts","detect","entries","local","conflicts","stale","duplicates",{"skillNo":113,"name":114,"nameZh":6,"description":115,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":116,"categories":117,"keywords":121,"publishedAt":40},"01M6HYAVMPM4SBDV60R2B5HPV8","skill-discovery","Search reusable OpenSpace skills locally, and browse cloud packages step by step when a cloud skill may help. Reusing proven skills saves tokens, improves reliability, and extends your capabilities beyond built-in tools.","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Fopenspace\u002Fhost_skills\u002Fskill-discovery\u002FSKILL.md",[118],{"categoryNo":119,"categoryName":120,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000023","Skill与智能体开发",[122,123,124,103,125,126,127,128,129,130,131,132,133,134],"skill discovery","discovery","reusable","step by step","tokens","packages","help","cloud","reliability","capabilities","browse","search","Tools",{"skillNo":136,"name":137,"nameZh":6,"description":138,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":139,"categories":140,"keywords":142,"publishedAt":40},"01M6HYAR811B3RB0M50RBEDGN6","delegate-task","Delegate tasks to OpenSpace — a full-stack autonomous worker for coding, DevOps, web research, and desktop automation, backed by an extensive MCP tool and skill library. Skills auto-improve through use, reducing token consumption over time. A cloud community lets agents share and collectively evolve reusable skills.","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Fopenspace\u002Fhost_skills\u002Fdelegate-task\u002FSKILL.md",[141],{"categoryNo":119,"categoryName":120,"taxonomyType":21,"taxonomyTypeDesc":22},[143,144,145,103,146,147,148,149,150,124,102,36,151,152,153,39,154,155,156,157],"delegate","task","delegate task","time","improve","desktop automation","worker","community","autonomous","tool","stack","share","tasks","automation","MCP",{"skillNo":159,"name":160,"nameZh":6,"description":161,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":162,"categories":163,"keywords":164,"publishedAt":40},"01M6HYAM9FSGV6E52AYENDQXYH","write-special-chars-ts-check","Workaround for write_file failures caused by special characters (apostrophes, backticks, template literals) using a Python heredoc script, plus a reliable TypeScript type-checking step that filters output to only the newly-written files to avoid being misled by pre-existing errors.","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Flegacy\u002Fv1\u002Fshowcase\u002Fskills\u002Fwrite-special-chars-ts-check\u002FSKILL.md",[],[165,166,167,168,169,170,171,172,173,27,174,175,176,177,39,178,179],"write special chars ts check","write","check","type","files","filters","only","template","file","typescript","output","Existing","type-checking","errors","script",{"skillNo":181,"name":182,"nameZh":6,"description":183,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":184,"categories":185,"keywords":186,"publishedAt":40},"01M6HYAH05HGV7SVWSVR8PJRQD","write-special-chars-readback","Workaround for write_file failures caused by special characters (apostrophes, backticks, template literals) using a Python heredoc script, with mandatory post-write verification via read_file and cleanup of \u002Ftmp helper scripts.","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Flegacy\u002Fv1\u002Fshowcase\u002Fskills\u002Fwrite-special-chars-readback\u002FSKILL.md",[],[187,188,166,83,39,179,189,190,191,192,193,172,173,194,195,27],"write special chars readback","readback","helper","post","via","scripts","read","verification","cleanup"]