AI编程工具cursor实战

cursor是anysphere公司推出的一款AI代码编辑器,基于GPT3.5,GPT4.0模型,支持python,Java,js等多种程序语言,通过自然语言的输入能自动生成代码。它还具备代码理解,重构,优化的能力。cursor主要的ai功能包括代码提示补全和交互式聊天,交互式聊天可以回答你的问题,和帮你自动生成代码。

免费版每月有50 个慢速优先的高级请求。pro版本订阅价格20$/月,每月 500 个快速优先的高级请求,无限制次数的慢速优先高级请求。Business版本订阅价格40$/月,主要是强制隐私和0数据保留,代码不会被提交用户训练。

本次实战通过实现一个合并excel的功能来看看cursor的自动编程能力。此次开发全程cursor自动生成代码,无人工手写一行代码。

功能需求:有多个excel文件,统计每个小组的绩效情况,其中第一个sheet页是一个汇总表格,记录小组的每个人的绩效分和绩效等级,后面的多个sheet页是按每个人名一个sheet页,记录详细的绩效打分情况。部门负责人需要汇总多个小组的绩效,那么就需把多个小组的excel文件合并成一个,并且有如下要求:第一个汇总页需要把每个小组的汇总页的内容合并,并且输出到合并后文件的第一个sheet页,其它的详细打分的sheet页,则只需要原样拷贝到新的excel文件中,作为一个单独的sheet页。

下面看看cursor ai如何一步一步实现。

第一次输入提示:将source目录下的excel文件合并成output目录下的目标excel文件,并按照目标文件的格式汇总。

这里我将要处理的源文件先放入了source文件夹,目标文件放入了output文件夹。第一次第输入提示语我提示的比较简单,想让他通过学习我的源文件和目标文件,来自动处理,发现这个是行不通的。生成代码如下:

import pandas as pd
import os
from pathlib import Path

def merge_excel_files(source_dir, output_dir, output_filename):
    """
    合并source目录下的所有Excel文件到output目录下的目标文件
    
    Args:
        source_dir (str): 源Excel文件所在目录
        output_dir (str): 输出目录
        output_filename (str): 输出文件名
    """
    # 确保输出目录存在
    Path(output_dir).mkdir(parents=True, exist_ok=True)
    
    # 获取所有Excel文件
    excel_files = []
    for file in os.listdir(source_dir):
        if file.endswith(('.xlsx', '.xls')):
            excel_files.append(os.path.join(source_dir, file))
    
    if not excel_files:
        print("源目录中没有找到Excel文件!")
        return
    
    # 读取并合并所有Excel文件
    all_data = []
    for file in excel_files:
        try:
            df = pd.read_excel(file)
            all_data.append(df)
            print(f"已读取文件: {file}")
        except Exception as e:
            print(f"读取文件 {file} 时出错: {str(e)}")
    
    # 合并所有数据框
    if all_data:
        merged_df = pd.concat(all_data, ignore_index=True)
        
        # 保存合并后的文件
        output_path = os.path.join(output_dir, output_filename)
        merged_df.to_excel(output_path, index=False)
        print(f"
所有文件已合并到: {output_path}")
        print(f"总行数: {len(merged_df)}")
    else:
        print("没有成功读取任何文件!")

if __name__ == "__main__":
    # 设置源目录和输出目录
    source_directory = "source"
    output_directory = "output"
    output_file = "merged_result.xlsx"
    
    # 执行合并操作
    merge_excel_files(source_directory, output_directory, output_file)

下面是他的实现思路:

自动查找source目录下所有的Excel文件(.xlsx和.xls格式)

使用pandas读取并合并所有Excel文件

将合并后的结果保存到output目录下

提供错误处理和进度提示

使用方法:

创建source目录并将需要合并的Excel文件放入其中

创建output目录(脚本会自动创建,如果不存在)

运行脚本

如果您需要对合并后的数据进行特定的格式处理,我们可以在合并数据后、保存之前添加相应的数据处理代码。请告诉我是否需要添加特定的数据处理逻辑?

另外,如果您有目标文件的具体格式要求,也请提供,我可以根据要求修改代码以确保输出符合特定格式。

他这里只是简单的读入了source目录下的excel文件,然后把内容全部合并,再输出。生成的效果是完全不符合预期的。从这里也看到,提示看来需要尽量的精确,它才能理解你要做的事情.

第二次改进后输入提示:将source目录下的excel文件合并成一个文件,并存放至output目录,合并规则:“汇总”sheet页中的内容合并至第一个sheet页,其它sheet页的内容不进行合并,直接拷贝到新的excel文件作为一个单独sheet页,并且保持原sheet页的格式。

生成代码:

import pandas as pd
import os
from pathlib import Path

def merge_excel_files():
    # 确保目录存在
    source_dir = Path('source')
    output_dir = Path('output')
    output_dir.mkdir(exist_ok=True)
    
    # 用于存储所有"汇总"sheet的数据
    summary_dfs = []
    # 用于存储其他sheet的数据和格式
    other_sheets = {}
    
    try:
        # 遍历source目录下的所有excel文件
        for excel_file in source_dir.glob('*.xlsx'):
            # 读取excel文件中的所有sheet
            excel = pd.ExcelFile(excel_file)
            
            # 读取并存储"汇总"sheet的数据
            if '汇总' in excel.sheet_names:
                df = pd.read_excel(excel, sheet_name='汇总', engine='openpyxl')
                summary_dfs.append(df)
            
            # 读取并存储其他sheet的数据
            for sheet_name in excel.sheet_names:
                if sheet_name != '汇总':
                    # 使用keep_vba=True保持原格式
                    df = pd.read_excel(excel, sheet_name=sheet_name, engine='openpyxl')
                    sheet_key = f"{sheet_name}_{len(other_sheets)}"
                    other_sheets[sheet_key] = df
        
        # 合并所有"汇总"sheet的数据
        merged_summary = pd.concat(summary_dfs, ignore_index=True) if summary_dfs else pd.DataFrame()
        
        # 创建输出文件
        output_file = output_dir / 'merged_excel.xlsx'
        with pd.ExcelWriter(output_file, engine='openpyxl') as writer:
            # 写入合并后的汇总数据
            if not merged_summary.empty:
                merged_summary.to_excel(writer, sheet_name='汇总', index=False)
            
            # 写入其他sheet页
            for sheet_name, df in other_sheets.items():
                df.to_excel(writer, sheet_name=sheet_name.split('_')[0], index=False)
        
        print(f"Excel文件已成功合并:{output_file}")
        
    except Exception as e:
        print(f"合并Excel文件时发生错误:{str(e)}")

if __name__ == '__main__':
    merge_excel_files()

实现思路:

创建了一个新的 merge_excel_files() 函数来处理Excel文件的合并

使用 Path 对象来处理文件路径

分别处理”汇总”sheet页和其他sheet页:

将所有文件中的”汇总”sheet页数据收集到一个列表中,最后合并

其他sheet页保持原样,但使用唯一的名称存储(添加序号避免重名)

使用 pd.ExcelWriter 创建新的Excel文件,将合并后的”汇总”数据和其他sheet页写入

使用方法:

在代码所在目录创建 source 文件夹

将需要合并的Excel文件放入 source 文件夹

运行程序,合并后的文件将保存在 output 文件夹中

注意:这个实现假设所有”汇总”sheet页的结构是一致的,如果结构不一致可能需要额外的处理逻辑。

这里基本上满足我们要求了。他还有一个提示,告诉你汇总页的字段格式需要对齐,还是有一定的智能了。但是还有一个问题。生成的新的excel文件,并没有保留原有格式。虽然我们提示语有要求他要保持原格式,但是貌似这个提示语他并未理解。

于是我们再做进一步改进,这次我们直接告诉他想要改进的地方,

第三次输入提示:读取excel sheet页内容,包含格式

改进后的代码:

import openpyxl
from pathlib import Path
from copy import copy

def copy_cell_format(source_cell, target_cell):
    """复制单元格格式"""
    if source_cell.has_style:
        target_cell.font = copy(source_cell.font)
        target_cell.border = copy(source_cell.border)
        target_cell.fill = copy(source_cell.fill)
        target_cell.number_format = copy(source_cell.number_format)
        target_cell.protection = copy(source_cell.protection)
        target_cell.alignment = copy(source_cell.alignment)

def merge_excel_files():
    source_dir = Path('source')
    output_dir = Path('output')
    output_dir.mkdir(exist_ok=True)
    
    # 创建新的工作簿
    merged_wb = openpyxl.Workbook()
    merged_wb.remove(merged_wb.active)  # 删除默认创建的sheet
    
    # 用于存储所有"汇总"sheet的数据和格式
    summary_cells = []
    max_summary_row = 0
    max_summary_col = 0
    
    try:
        # 遍历source目录下的所有excel文件
        for excel_file in source_dir.glob('*.xlsx'):
            wb = openpyxl.load_workbook(excel_file, data_only=True)
            
            # 处理"汇总"sheet
            if '汇总' in wb.sheetnames:
                summary_sheet = wb['汇总']
                # 获取该sheet的使用范围
                for row in summary_sheet.rows:
                    row_data = []
                    for cell in row:
                        row_data.append({
                            'value': cell.value,
                            'cell': cell
                        })
                    summary_cells.append(row_data)
                    max_summary_col = max(max_summary_col, len(row_data))
                max_summary_row = max(max_summary_row, len(summary_cells))
            
            # 复制其他sheet
            for sheet_name in wb.sheetnames:
                if sheet_name != '汇总':
                    source_sheet = wb[sheet_name]
                    # 创建新的sheet,添加序号避免重名
                    new_sheet_name = f"{sheet_name}_{len(merged_wb.sheetnames)}"
                    target_sheet = merged_wb.create_sheet(title=new_sheet_name)
                    
                    # 复制列宽
                    for col in range(1, source_sheet.max_column + 1):
                        target_sheet.column_dimensions[openpyxl.utils.get_column_letter(col)].width = 
                            source_sheet.column_dimensions[openpyxl.utils.get_column_letter(col)].width
                    
                    # 复制行高
                    for row in range(1, source_sheet.max_row + 1):
                        target_sheet.row_dimensions[row].height = 
                            source_sheet.row_dimensions[row].height
                    
                    # 复制单元格内容和格式
                    for row in source_sheet.rows:
                        for cell in row:
                            new_cell = target_sheet.cell(
                                row=cell.row, 
                                column=cell.column,
                                value=cell.value
                            )
                            copy_cell_format(cell, new_cell)
                    
                    # 复制合并单元格
                    for merged_range in source_sheet.merged_cells.ranges:
                        target_sheet.merge_cells(str(merged_range))
        
        # 创建合并后的汇总sheet
        if summary_cells:
            summary_sheet = merged_wb.create_sheet(title='汇总', index=0)
            
            # 写入汇总数据和格式
            for row_idx, row_data in enumerate(summary_cells, 1):
                for col_idx, cell_data in enumerate(row_data, 1):
                    new_cell = summary_sheet.cell(
                        row=row_idx,
                        column=col_idx,
                        value=cell_data['value']
                    )
                    copy_cell_format(cell_data['cell'], new_cell)
        
        # 保存合并后的文件
        output_file = output_dir / 'merged_excel.xlsx'
        merged_wb.save(output_file)
        print(f"Excel文件已成功合并:{output_file}")
        
    except Exception as e:
        print(f"合并Excel文件时发生错误:{str(e)}")

if __name__ == '__main__':
    merge_excel_files()

生成后的提示:

主要更新内容:

添加了文件格式验证函数 is_valid_excel()

增加了对 .xls 和 .xlsx 两种格式的支持

添加了更详细的错误处理和日志输出

增加了文件处理进度提示

添加了资源清理(关闭工作簿)

优化了列宽和行高的复制逻辑,增加了存在性检查

对格式复制操作添加了异常处理

使用方法:

确保已安装必要的库:pip install openpyxl

准备文件:

创建 source 文件夹

将需要合并的Excel文件放入 source 文件夹

确保Excel文件格式正确且未被损坏

运行程序,程序会:

显示处理进度

报告任何错误

将合并后的文件保存在 output 文件夹中

如果仍然遇到问题,请检查:

Excel文件是否可以正常打开

文件是否被其他程序占用

是否有足够的权限访问这些文件

我们看到,这里我们的输入并不是完成的程序的逻辑,但是他能根据你之前的提示输入,结合上下文对代码进行改进,这一点还是非常不错的。而且他还有使用提示,可能出现的问题都会列出来。

到这里这个excel合并程序基本上满足我们的要求了。从这个程序的生成过程,我们可以看到,cursor可以以一种交互式的沟通模式,不断优化改进你的程序,生成的代码几乎是能直接运行的代码,错误率非常低。碰到一些异常情况,也可以将异常作为一次提问,他能够给你输出改进后的代码。我们使用好他的关键还是需要不断磨练和总结我们的输入提示词,反而淡化真正程序侧的东西。有点趋向于产品经理能使用的编程工具了。至少对于这种工具或者组件类的程序,cursor还是表现的非常强大和智能。对于偏向业务侧的编程,以及对于原因项目代码的理解,我们还要通过进一步测试验证才能判断。

© 版权声明
THE END
如果内容对您有所帮助,就支持一下吧!
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容