如何使用C++处理Excel文件?新手如何通过fstream操作表格行列
关于C++用fstream操作Excel表格的说明
首先明确一个前提:原生fstream 无法直接解析.xlsx 格式的Excel二进制文件,你能通过纯文本流处理的是CSV格式文件——这是一种逗号分隔的纯文本格式,Excel可以直接打开、识别和编辑,完全满足基础的数值写入需求。
定位指定行/列的实现逻辑
CSV的格式规则非常简单:
- 每一行文本对应Excel的一行数据
- 同一行内的不同列用逗号(也可以用制表符等自定义分隔符)分隔
基于这个规则,你可以按如下方法定位目标位置:
- 定位指定行:调用
std::getline逐行读取文件内容,同时计数行数,读到和你目标行号一致的内容时停止即可 - 定位指定列:拿到目标行的完整字符串后,按分隔符切割字符串,切割后得到的数组中,下标对应列号的元素就是目标列内容
写入指定位置的示例代码
如果是小体积的CSV文件,最简单的实现方式是把所有内容读入内存修改后再回写,示例如下:
#include <fstream> #include <vector> #include <string> #include <sstream> // 按分隔符切割字符串的工具函数 std::vector<std::string> split(const std::string& s, char delimiter) { std::vector<std::string> tokens; std::string token; std::istringstream tokenStream(s); while (std::getline(tokenStream, token, delimiter)) { tokens.push_back(token); } return tokens; } int main() { const std::string file_path = "test.csv"; const int target_row = 2; // 行号从0开始计数,对应Excel的第3行 const int target_col = 1; // 列号从0开始计数,对应Excel的第2列 const std::string write_value = "12345"; // 1. 读取所有行内容到内存 std::vector<std::vector<std::string>> all_rows; std::ifstream in_file(file_path); std::string line; while (std::getline(in_file, line)) { all_rows.push_back(split(line, ',')); } in_file.close(); // 2. 检查目标位置是否存在,不存在则补全空行/空列 if (target_row >= all_rows.size()) { all_rows.resize(target_row + 1); } if (target_col >= all_rows[target_row].size()) { all_rows[target_row].resize(target_col + 1); } // 3. 写入目标数值 all_rows[target_row][target_col] = write_value; // 4. 把修改后的内容回写到文件 std::ofstream out_file(file_path); for (size_t i = 0; i < all_rows.size(); i++) { for (size_t j = 0; j < all_rows[i].size(); j++) { if (j > 0) out_file << ","; out_file << all_rows[i][j]; } out_file << "\n"; } out_file.close(); return 0; }
注意事项
- 如果你的CSV内容中本身包含逗号,需要给对应字段套上双引号避免切割出错,示例代码没有处理这种边界场景,你可以根据自己的需求扩展
- 如果你需要直接操作
.xlsx格式文件,不能用原生fstream实现,需要引入第三方库比如OpenXLSX、libxl等
内容的提问来源于stack exchange,提问作者Lasindu Kashmira
相关产品推荐
相关产品推荐

