使用 Cells 和数据模型
使用单元格和数据模型
Cell 类是读取和写入各个电子表格单元格值、公式和样式的主要接口。使用地址字符串通过工作表的 Cells 集合访问单元格。
向单元格写入值
使用 Cell::PutValue 将文本、数字、布尔值或日期写入单元格:
#include "aspose/cells_foss/Workbook.h"
#include "aspose/cells_foss/Worksheet.h"
#include "aspose/cells_foss/Cell.h"
using namespace Aspose::Cells_FOSS;
int main() {
Workbook workbook;
Worksheet& sheet = workbook.GetWorksheets()[0];
sheet.GetCells()["A1"].PutValue("Product");
sheet.GetCells()["B1"].PutValue("Price");
sheet.GetCells()["A2"].PutValue("Widget");
sheet.GetCells()["B2"].PutValue(9.99);
sheet.GetCells()["C2"].PutValue(true);
workbook.Save("data.xlsx");
return 0;
}设置公式
使用 Cell::SetFormula(formula) 编写兼容 Excel 的公式。文件打开时,公式将由 Excel 或兼容的读取器进行求值。
sheet.GetCells()["B4"].SetFormula("=SUM(B2:B3)");
sheet.GetCells()["C4"].SetFormula("=AVERAGE(B2:B3)");读取单元格值
使用 Cell::GetValue() 读取单元格的当前值,该方法返回一个 CellValue 对象。使用相应的访问器将其转换为特定类型:
CellValue val = sheet.GetCells()["B2"].GetValue();
double price = val.AsDouble();
std::string text = sheet.GetCells()["A2"].GetStringValue();CellValue 类提供了类型化访问器:
| 方法 | 返回类型 |
|---|---|
AsDouble() | double |
AsInteger() | int |
AsBool() | bool |
AsString() | std::string |
AsDateTime() | DateTime |
按行和列访问单元格
除了地址字符串外,还可以使用从零开始的行列索引访问单元格:
// Address string
Cell& cellA1 = sheet.GetCells()["A1"];
// Row/column index (0-based)
int row = cellA1.GetRow();
int col = cellA1.GetColumn();合并单元格
使用 Cells::Merge 将矩形范围的单元格合并为一个:
CellArea area = CellArea::CreateCellArea("A1", "C1");
sheet.GetCells().Merge(area.StartRow, area.StartColumn,
area.EndRow - area.StartRow + 1,
area.EndColumn - area.StartColumn + 1);获取显示文本
要将单元格值检索为已格式化的显示文本(应用数字格式),请使用 Cell::GetDisplayStringValue():
std::string display = sheet.GetCells()["B2"].GetDisplayStringValue();提示和最佳实践
- 在直接字面量赋值时,优先使用
PutValue而不是SetValue——PutValue为所有原始类型提供了重载。 - 使用
GetStringValue()获取文本而不进行类型转换;当需要数值精度时,请使用GetValue().AsDouble()。 - 对于公式单元格始终调用
SetFormula,而不是PutValue("=SUM(...)")—— 后者存储的是字符串字面量,而不是公式。 - 使用
CellArea::CreateCellArea(start, end)构建范围对象,以进行合并和格式化操作。
常见问题
| 问题 | 原因 | 解决方法 |
|---|---|---|
GetValue() 返回为空 | 单元格尚未写入 | 在读取之前使用 PutValue 写入一个值 |
| 公式未求值 | 公式已保存为字符串 | 请使用 SetFormula(expr) 而不是 PutValue(expr) |
| 合并失败 | 范围维度无效 | 确保 endRow >= startRow 和 endColumn >= startColumn |
| 读取时类型不匹配 | 调用了错误的 As*() 方法 | 将访问器匹配到原始的 PutValue 类型 |
API Reference 概要
| 类/方法 | 描述 |
|---|---|
Cell::PutValue(value) | 向单元格写入字面值 |
Cell::SetFormula(formula) | 设置 Excel 公式字符串 |
Cell::GetValue() | 以 CellValue 的形式检索单元格值 |
Cell::GetStringValue() | 检索单元格值为字符串 |
Cell::GetDisplayStringValue() | 检索格式化显示字符串 |
Cell::GetRow() | 获取零基行索引 |
Cell::GetColumn() | 获取零基列索引 |
Cell::GetStyle() | 获取当前单元格样式 |
Cell::SetStyle(style) | 对单元格应用修改后的样式 |
CellValue::AsDouble() | 将单元格值转换为 double |
CellValue::AsString() | 将单元格值转换为 string |
Cells::Merge(row, col, rows, cols) | 合并矩形范围 |