月底做报表是噩梦。以前2小时做一份,现在用Python+AI,5分钟搞定。分享完整代码。


一、核心思路

用Python调用AI API生成Excel公式,再用openpyxl自动化生成报表。


二、完整代码

```python
# auto_excel.py
import openai
import openpyxl
from openpyxl.styles import Font, PatternFill
import os

class AutoExcel:
def __init__(self):
        self.client = openai.OpenAI(
            api_key=os.getenv("DEEPSEEK_KEY"),
            base_url="https://api.deepseek.com/v1"
        )
  
def generate_formula(self, requirement):
"""AI生成Excel公式"""
        response = self.client.chat.completions.create(
            model="deepseek-chat",
            messages=[
                {"role": "system", "content": "你是Excel专家"},
                {"role": "user", "content": f"生成Excel公式:{requirement}"}
            ],
            temperature=0.3
        )
        return response.choices[0].message.content
  
def create_report(self, data_file, output_file):
"""生成报表"""
        wb = openpyxl.Workbook()
        ws = wb.active
        ws.title = "销售报表"
      
# 表头
        headers = ["月份", "销售额", "增长率", "同比"]
        for col, header in enumerate(headers, 1):
            cell = ws.cell(row=1, column=col, value=header)
            cell.font = Font(bold=True)
            cell.fill = PatternFill(start_color="4472C4", end_color="4472C4", fill_type="solid")
      
# 数据(示例)
        data = [
            ["1月", 100000, "=B2/B1-1", "=B2/100000-1"],
            ["2月", 120000, "=B3/B2-1", "=B3/100000-1"],
        ]
      
        for row_idx, row_data in enumerate(data, 2):
            for col_idx, value in enumerate(row_data, 1):
                ws.cell(row=row_idx, column=col_idx, value=value)
      
wb.save(output_file)
        print(f"报表已保存:{output_file}")

# 使用示例
if __name__ == "__main__":
    excel = AutoExcel()
  
# 生成公式
    formula = excel.generate_formula("计算销售额环比增长率")
print("公式:", formula)
  
# 生成报表
excel.create_report("data.xlsx", "report.xlsx")

三、运行效果

$ python auto_excel.py
公式:=(本月-上月)/上月

报表已保存:report.xlsx

用时:5分钟(以前2小时)
效率提升:24倍

四、踩坑记录

解决
公式错误 AI生成后人工验证
格式乱 用openpyxl固定样式
数据量大 分批次处理

标签:Python,Excel自动化,AI,财务效率,openpyxl,实战教程

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐