一、简介

官网:https://github.com/tfussell/xlnt
Cross-platform user-friendly xlsx library for C++11+

xlnt is a modern C++ library for manipulating spreadsheets in memory and reading/writing them from/to XLSX files as described in ECMA 376 4th edition. The first public release of xlnt version 1.0 was on May 10th, 2017. Current work is focused on increasing compatibility, improving performance, and brainstorming future development goals. For a high-level summary of what you can do with this library, see the feature list. Contributions are welcome in the form of pull requests or discussions on the repository’s Issues page.

xlnt 是一个现代 C++ 库,用于在内存中操作电子表格,并按照 ECMA 376 第 4 版中的描述,从 XLSX 文件中读取/写入电子表格。xlnt 1.0 版本于 2017 年 5 月 10 日首次公开发布。目前的工作重点是增强兼容性、提高性能,以及集思广益制定未来的开发目标。

二、基本用法

1. 生成excel

#include int main(){xlnt::workbook wb;xlnt::worksheet ws = wb.active_sheet();ws.cell("A1").value(5);ws.cell("B2").value("string data");ws.cell("C3").formula("=RAND()");ws.merge_cells("C3:C4");ws.freeze_panes("B2");wb.save("example.xlsx");return 0;}

2. 读取指定表单

xlnt::workbook wb;wb.load("example.xlsx"); // 加载 Excel 文件// 通过名称获取指定的工作表xlnt::worksheet ws = wb.sheet("Sheet1");// xlnt::worksheet ws = wb.sheet(u8"中文");// 也可以通过索引获取指定的工作表,索引从 0 开始// xlnt::worksheet ws = wb.sheet(0);std::cout << "正在读取工作表: " << ws.title() << std::endl;

3. 读取指定单元格

// 读取 A1 单元格的值auto cell_value = ws.cell("A1").value();auto cell_value = ws.cell(xlnt::cell_reference(1, 1)).value();auto cell_value = ws.cell(1, 1).value();

4. 获取行数或列数

// 获取行数auto row_count = ws.rows();// 获取列数auto column_count = ws.columns();

5. 读取指定范围

#include #include #include int main() {xlnt::workbook wb;wb.load("example.xlsx"); // 加载 Excel 文件auto ws = wb.active_sheet();std::vector<std::string> row_data;// 读取第1行的数据for (const auto& cell : ws.range("1:1")) {row_data.push_back(cell.to_string());}// 打印第1行的数据for (const auto& data : row_data) {std::cout << data << " ";}return 0;}

三、进阶用法

1. 设置字体

// 创建一个字体对象并设置字体大小和样式xlnt::font font;font.size(12); // 设置字体大小为12font.bold(true); // 设置为粗体font.italic(true); // 设置为斜体font.color(xlnt::color::red()); // 设置字体颜色为红色// 获取要设置字体的单元格auto cell = ws.cell("A1");// 将字体对象应用于单元格cell.font(font);

2. 设置填充色

// 创建一个填充对象并设置颜色xlnt::fill fill;fill.pattern_type(xlnt::pattern_fill_type::solid);fill.foreground(xlnt::color::green());// 获取要设置背景色的单元格auto cell = ws.cell("A1");// 将填充对象应用于单元格cell.fill(fill);

3. 设置行高与列宽

// 设置行高ws.row_properties(1).height = 30; // 第1行高度为30像素// 设置列宽ws.column_properties(1).width = 20; // 第1列宽度为20