xlsx by tfriedel/claude-office-skills
npx skills add https://github.com/tfriedel/claude-office-skills --skill xlsx除非用户或现有模板另有说明
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
用户可能会要求您创建、编辑或分析 .xlsx 文件的内容。针对不同的任务,您可以使用不同的工具和工作流程。
公式重新计算需要 LibreOffice :您可以假设已安装 LibreOffice,以便使用 recalc.py 脚本重新计算公式值。该脚本在首次运行时会自动配置 LibreOffice。
对于数据分析、可视化和基本操作,请使用 pandas,它提供了强大的数据处理能力:
import pandas as pd
# 读取 Excel
df = pd.read_excel('file.xlsx') # 默认:第一个工作表
all_sheets = pd.read_excel('file.xlsx', sheet_name=None) # 所有工作表作为字典
# 分析
df.head() # 预览数据
df.info() # 列信息
df.describe() # 统计信息
# 写入 Excel
df.to_excel('output.xlsx', index=False)
始终使用 Excel 公式,而不是在 Python 中计算值并硬编码。 这确保了电子表格保持动态性和可更新性。
# 错误:在 Python 中计算并硬编码结果
total = df['Sales'].sum()
sheet['B10'] = total # 硬编码 5000
# 错误:在 Python 中计算增长率
growth = (df.iloc[-1]['Revenue'] - df.iloc[0]['Revenue']) / df.iloc[0]['Revenue']
sheet['C5'] = growth # 硬编码 0.15
# 错误:在 Python 中计算平均值
avg = sum(values) / len(values)
sheet['D20'] = avg # 硬编码 42.5
# 正确:让 Excel 计算总和
sheet['B10'] = '=SUM(B2:B9)'
# 正确:将增长率作为 Excel 公式
sheet['C5'] = '=(C4-C2)/C2'
# 正确:使用 Excel 函数计算平均值
sheet['D20'] = '=AVERAGE(D2:D19)'
这适用于所有计算 - 总计、百分比、比率、差值等。当源数据更改时,电子表格应能够重新计算。
选择工具 :数据分析用 pandas,公式/格式用 openpyxl
创建/加载 :创建新工作簿或加载现有文件
修改 :添加/编辑数据、公式和格式
保存 :写入文件
重新计算公式(如果使用公式,则此项为强制步骤) :使用 recalc.py 脚本
python recalc.py output.xlsx
验证并修复任何错误 :
status 为 errors_found,请检查 error_summary 以获取具体的错误类型和位置#REF!:无效的单元格引用#DIV/0!:除以零#VALUE!:公式中使用了错误的数据类型#NAME?:无法识别的公式名称# 使用 openpyxl 处理公式和格式
from openpyxl import Workbook
from openpyxl.styles import Font, PatternFill, Alignment
wb = Workbook()
sheet = wb.active
# 添加数据
sheet['A1'] = 'Hello'
sheet['B1'] = 'World'
sheet.append(['Row', 'of', 'data'])
# 添加公式
sheet['B2'] = '=SUM(A1:A10)'
# 格式化
sheet['A1'].font = Font(bold=True, color='FF0000')
sheet['A1'].fill = PatternFill('solid', start_color='FFFF00')
sheet['A1'].alignment = Alignment(horizontal='center')
# 列宽
sheet.column_dimensions['A'].width = 20
wb.save('output.xlsx')
# 使用 openpyxl 以保留公式和格式
from openpyxl import load_workbook
# 加载现有文件
wb = load_workbook('existing.xlsx')
sheet = wb.active # 或 wb['SheetName'] 用于特定工作表
# 处理多个工作表
for sheet_name in wb.sheetnames:
sheet = wb[sheet_name]
print(f"Sheet: {sheet_name}")
# 修改单元格
sheet['A1'] = 'New Value'
sheet.insert_rows(2) # 在第2行插入行
sheet.delete_cols(3) # 删除第3列
# 添加新工作表
new_sheet = wb.create_sheet('NewSheet')
new_sheet['A1'] = 'Data'
wb.save('modified.xlsx')
由 openpyxl 创建或修改的 Excel 文件包含作为字符串的公式,但不包含计算值。使用提供的 recalc.py 脚本重新计算公式:
python recalc.py <excel_file> [timeout_seconds]
示例:
python recalc.py output.xlsx 30
该脚本:
确保公式正确工作的快速检查:
pd.notna() 检查空值/ 之前检查分母(#DIV/0!)脚本返回包含错误详情的 JSON:
{
"status": "success", // 或 "errors_found"
"total_errors": 0, // 错误总数
"total_formulas": 42, // 文件中的公式数量
"error_summary": { // 仅在发现错误时存在
"#REF!": {
"count": 2,
"locations": ["Sheet1!B5", "Sheet1!C10"]
}
}
}
data_only=True 读取计算值:load_workbook('file.xlsx', data_only=True)data_only=True 打开并保存,公式将被值替换并永久丢失read_only=True,写入时使用 write_only=Truepd.read_excel('file.xlsx', dtype={'id': str})pd.read_excel('file.xlsx', usecols=['A', 'C', 'E'])pd.read_excel('file.xlsx', parse_dates=['date_column'])重要 :当为 Excel 操作生成 Python 代码时:
对于 Excel 文件本身 :
每周安装量
1.7K
仓库
GitHub 星标数
428
首次出现
Jan 24, 2026
安全审计
安装于
opencode1.5K
gemini-cli1.5K
codex1.5K
github-copilot1.4K
kimi-cli1.4K
amp1.4K
Unless otherwise stated by the user or existing template
A user may ask you to create, edit, or analyze the contents of an .xlsx file. You have different tools and workflows available for different tasks.
LibreOffice Required for Formula Recalculation : You can assume LibreOffice is installed for recalculating formula values using the recalc.py script. The script automatically configures LibreOffice on first run
For data analysis, visualization, and basic operations, use pandas which provides powerful data manipulation capabilities:
import pandas as pd
# Read Excel
df = pd.read_excel('file.xlsx') # Default: first sheet
all_sheets = pd.read_excel('file.xlsx', sheet_name=None) # All sheets as dict
# Analyze
df.head() # Preview data
df.info() # Column info
df.describe() # Statistics
# Write Excel
df.to_excel('output.xlsx', index=False)
Always use Excel formulas instead of calculating values in Python and hardcoding them. This ensures the spreadsheet remains dynamic and updateable.
# Bad: Calculating in Python and hardcoding result
total = df['Sales'].sum()
sheet['B10'] = total # Hardcodes 5000
# Bad: Computing growth rate in Python
growth = (df.iloc[-1]['Revenue'] - df.iloc[0]['Revenue']) / df.iloc[0]['Revenue']
sheet['C5'] = growth # Hardcodes 0.15
# Bad: Python calculation for average
avg = sum(values) / len(values)
sheet['D20'] = avg # Hardcodes 42.5
# Good: Let Excel calculate the sum
sheet['B10'] = '=SUM(B2:B9)'
# Good: Growth rate as Excel formula
sheet['C5'] = '=(C4-C2)/C2'
# Good: Average using Excel function
sheet['D20'] = '=AVERAGE(D2:D19)'
This applies to ALL calculations - totals, percentages, ratios, differences, etc. The spreadsheet should be able to recalculate when source data changes.
Choose tool : pandas for data, openpyxl for formulas/formatting
Create/Load : Create new workbook or load existing file
Modify : Add/edit data, formulas, and formatting
Save : Write to file
Recalculate formulas (MANDATORY IF USING FORMULAS) : Use the recalc.py script
python recalc.py output.xlsx
Verify and fix any errors :
status is errors_found, check error_summary for specific error types and locations#REF!: Invalid cell references# Using openpyxl for formulas and formatting
from openpyxl import Workbook
from openpyxl.styles import Font, PatternFill, Alignment
wb = Workbook()
sheet = wb.active
# Add data
sheet['A1'] = 'Hello'
sheet['B1'] = 'World'
sheet.append(['Row', 'of', 'data'])
# Add formula
sheet['B2'] = '=SUM(A1:A10)'
# Formatting
sheet['A1'].font = Font(bold=True, color='FF0000')
sheet['A1'].fill = PatternFill('solid', start_color='FFFF00')
sheet['A1'].alignment = Alignment(horizontal='center')
# Column width
sheet.column_dimensions['A'].width = 20
wb.save('output.xlsx')
# Using openpyxl to preserve formulas and formatting
from openpyxl import load_workbook
# Load existing file
wb = load_workbook('existing.xlsx')
sheet = wb.active # or wb['SheetName'] for specific sheet
# Working with multiple sheets
for sheet_name in wb.sheetnames:
sheet = wb[sheet_name]
print(f"Sheet: {sheet_name}")
# Modify cells
sheet['A1'] = 'New Value'
sheet.insert_rows(2) # Insert row at position 2
sheet.delete_cols(3) # Delete column 3
# Add new sheet
new_sheet = wb.create_sheet('NewSheet')
new_sheet['A1'] = 'Data'
wb.save('modified.xlsx')
Excel files created or modified by openpyxl contain formulas as strings but not calculated values. Use the provided recalc.py script to recalculate formulas:
python recalc.py <excel_file> [timeout_seconds]
Example:
python recalc.py output.xlsx 30
The script:
Quick checks to ensure formulas work correctly:
pd.notna()/ in formulas (#DIV/0!)The script returns JSON with error details:
{
"status": "success", // or "errors_found"
"total_errors": 0, // Total error count
"total_formulas": 42, // Number of formulas in file
"error_summary": { // Only present if errors found
"#REF!": {
"count": 2,
"locations": ["Sheet1!B5", "Sheet1!C10"]
}
}
}
data_only=True to read calculated values: load_workbook('file.xlsx', data_only=True)data_only=True and saved, formulas are replaced with values and permanently lostread_only=True for reading or write_only=True for writingpd.read_excel('file.xlsx', dtype={'id': str})pd.read_excel('file.xlsx', usecols=['A', 'C', 'E'])pd.read_excel('file.xlsx', parse_dates=['date_column'])IMPORTANT : When generating Python code for Excel operations:
For Excel files themselves :
Weekly Installs
1.7K
Repository
GitHub Stars
428
First Seen
Jan 24, 2026
Security Audits
Gen Agent Trust HubWarnSocketPassSnykPass
Installed on
opencode1.5K
gemini-cli1.5K
codex1.5K
github-copilot1.4K
kimi-cli1.4K
amp1.4K
React 组合模式指南:Vercel 组件架构最佳实践,提升代码可维护性
102,200 周安装
#DIV/0!: Division by zero#VALUE!: Wrong data type in formula#NAME?: Unrecognized formula name