You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CAPL编程:如何从CSV文件读取指定列与指定行数据

CAPL读取CSV文件特定列/行范围数据的实现

CAPL没有内置CSV解析工具,需要自定义字符串拆分函数处理行列数据,以下是针对两种需求的实现方案:

工具函数:拆分CSV行数据

先实现通用的字符串拆分函数,按指定分隔符将单行内容拆分为列数组:

// 按分隔符拆分字符串到数组,返回拆分后的列数
long split(char str[], char delimiter, char result[][256], long maxElements)
{
    long i = 0;
    char* token = strtok(str, delimiter);
    while(token != NULL && i < maxElements)
    {
        strncpy(result[i], token, 255);
        result[i][255] = '\0';
        token = strtok(NULL, delimiter);
        i++;
    }
    return i;
}

需求1:提取第72至84列的所有行数据

注意CAPL数组索引从0开始,因此第72列对应索引71,第84列对应索引83:

void readColumns72To84(char filename[])
{
    fileHandle fh;
    char line[1024];
    char columns[100][256]; // 根据实际CSV列数调整数组大小
    long columnCount;
    const long startColIdx = 71;
    const long endColIdx = 83;

    fh = fileOpen(filename, "r");
    if(fh == 0)
    {
        write("无法打开文件: %s", filename);
        return;
    }

    // 逐行读取处理
    while(fileReadLine(line, 1023, fh))
    {
        columnCount = split(line, ",", columns, 100);
        // 检查当前行列数是否满足需求
        if(columnCount <= endColIdx)
        {
            write("当前行列数不足,跳过该行");
            continue;
        }
        // 输出指定列数据
        write("当前行指定列数据:");
        for(long i = startColIdx; i <= endColIdx; i++)
        {
            write("列%d: %s", i+1, columns[i]); // i+1转换为1起始的列号
        }
        write("---");
    }

    fileClose(fh);
}

需求2:读取第89行到第99行的A列数据

A列即第1列,对应索引0;行号按用户习惯的1起始计数:

void readRows89To99ColumnA(char filename[])
{
    fileHandle fh;
    char line[1024];
    char columns[100][256];
    long currentRow = 0;
    const long targetStartRow = 89;
    const long targetEndRow = 99;
    const long targetColIdx = 0; // A列对应索引0

    fh = fileOpen(filename, "r");
    if(fh == 0)
    {
        write("无法打开文件: %s", filename);
        return;
    }

    // 逐行读取,定位目标行范围
    while(fileReadLine(line, 1023, fh))
    {
        currentRow++;
        // 跳过目标范围之前的行
        if(currentRow < targetStartRow) continue;
        // 超出目标范围则终止读取
        if(currentRow > targetEndRow) break;
        // 提取并输出目标列数据
        split(line, ",", columns, 100);
        write("第%d行A列数据: %s", currentRow, columns[targetColIdx]);
    }

    fileClose(fh);
}

注意事项

  • 如果CSV使用分号等其他分隔符,修改split函数的delimiter参数即可。
  • 根据实际CSV的行长度、列数,调整line、columns数组的大小。
  • 若CSV包含表头行,可在读取时判断currentRow == 1时跳过该行。

内容的提问来源于stack exchange,提问作者Linta Joseph

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 21:39:18