介绍
电子表格管理是 Aspose.Cells FOSS 在 C++ 中的一个部分,几乎所有程序首先接触到的内容:拥有文件的 Workbook、其中的 Worksheet 对象,以及保存数值、公式和格式的 Cells 集合。本文比一般介绍更深入地探讨了这一层面——工作簿和工作表的创建与导航、单元格数值和公式的读取与写入、Style、Font、Color 与 Borders 如何组合以格式化输出,以及 PageSetup、Hyperlink、DefinedName 与 Validation 如何在原始单元格网格周围添加结构。
此处涉及的每个类都是原生 C++ API,在 aspose/cells_foss/ 头文件下声明。它不使用 COM 互操作,也不依赖于安装 Microsoft Excel —— 库直接读取和写入 .xlsx 包格式,这也是当前版本仅支持 .xlsx 的原因,无论是加载还是保存。
下面的示例相互依赖:创建工作簿、填充工作表和单元格、应用样式,然后保存文件并重新加载以确认往返无误。所有代码均改编自库自身的兼容性、黄金以及单元测试套件,因此它们反映了针对真实 .xlsx 输出的实际操作。
关键特性
工作簿和工作表管理
一个 Workbook 在其 WorksheetCollection 中默认包含一个工作表。工作表可通过 Add() 添加,可按索引或名称查找,并可使用 SetName() 重命名。WorksheetCollection 还会跟踪当前活动的工作表:
#include "aspose/cells_foss/Workbook.h"
#include "aspose/cells_foss/Worksheet.h"
using namespace Aspose::Cells_FOSS;
Workbook workbook;
Worksheet& sheet = workbook.GetWorksheets()[0];
sheet.SetName("Data");
int summaryIndex = workbook.GetWorksheets().Add("Summary");
workbook.GetWorksheets().SetActiveSheetIndex(0);
int sheetCount = workbook.GetWorksheets().GetCount(); // 2
保存和重新加载使用相同的 Workbook 类型。Workbook::Save() 接受文件路径,而 Workbook 可以直接从路径或内存字节缓冲区构建,从而往返传递单元格值和公式:
workbook.Save("report.xlsx");
Workbook loaded("report.xlsx");
Worksheet& reloadedSheet = loaded.GetWorksheets()["Data"];
单元格值和公式
Cells,通过 Worksheet::GetCells() 访问,以 A1 样式引用索引单元格。Cell::PutValue() 接受字符串、整数、双精度和布尔值,SetFormula() 存储 Excel 公式字符串,GetValue() 返回一个带有类型化访问器的 CellValue(AsString()、AsInteger()、AsDouble()、AsBool()、AsDateTime()):
Cells& cells = sheet.GetCells();
cells["A1"].PutValue("Category");
cells["B1"].PutValue("Amount");
cells["A2"].PutValue("Travel");
cells["B2"].PutValue(482.50);
cells["A3"].PutValue("Supplies");
cells["B3"].PutValue(129.99);
cells["B4"].SetFormula("=SUM(B2:B3)");
CellValue amount = cells["B2"].GetValue();
if (amount.IsDouble()) {
double value = amount.AsDouble();
}
std::string formula = cells["B4"].GetFormula();
Cell::GetType() 报告存储的 CellValueType(Blank、String、Number、Boolean、DateTime 或 Formula),而 GetDisplayStringValue() 返回在 Excel 中显示的格式化值,遵循通过 Style 应用的任何数字格式。
使用 Style、Font、Color 和 Borders 进行样式设置
Cell::GetStyle() 返回一个可修改并可通过 SetStyle() 重新应用的 Style 对象。Style 暴露一个 Font、一组 Borders、填充图案和颜色、对齐方式以及数字格式:
#include "aspose/cells_foss/Style.h"
#include "aspose/cells_foss/Color.h"
Cell headerCell = sheet.GetCells()["A1"];
Style style = headerCell.GetStyle();
Font font = style.GetFont();
font.SetBold(true);
font.SetColor(Color::FromArgb(255, 255, 255, 255));
style.SetFont(font);
style.SetPattern(FillPattern::Solid);
style.SetForegroundColor(Color::FromArgb(255, 34, 120, 212));
style.SetHorizontalAlignment(HorizontalAlignmentType::Center);
Borders borders = style.GetBorders();
Border bottomBorder = borders.GetBottom();
bottomBorder.SetLineStyle(BorderStyleType::Thin);
borders.SetBottom(bottomBorder);
style.SetBorders(borders);
style.SetNumberFormat("#,##0.00");
headerCell.SetStyle(style);
Style 是一种值类型:使用 GetStyle() 读取它会反映最后一次通过 SetStyle() 设置的内容,这使得构建单一样式并将其应用于标题行或一系列数据单元格变得非常简便。
页面设置和打印配置
Worksheet::GetPageSetup() 返回一个 PageSetup 对象,覆盖纸张尺寸、方向、边距、缩放、打印标题和分页:
#include "aspose/cells_foss/PageSetup.h"
PageSetup& pageSetup = sheet.GetPageSetup();
pageSetup.SetOrientation(PageOrientationType::Landscape);
pageSetup.SetPaperSize(PaperSizeType::PaperA4);
pageSetup.SetFitToPagesWide(1);
pageSetup.SetFitToPagesTall(0);
pageSetup.SetPrintArea("$A$1:$D$20");
pageSetup.SetPrintTitleRows("$1:$1");
pageSetup.SetLeftMargin(0.5);
pageSetup.SetCenterFooter("Page &P of &N");
pageSetup.AddHorizontalPageBreak(20);
边距既可以使用原始单位(GetLeftMargin())也可以使用英寸(GetLeftMarginInch()),GetHorizontalPageBreaks() / GetVerticalPageBreaks() 返回当前在工作表上设置的分页位置。
超链接、已定义名称和数据验证
Worksheet::GetHyperlinks() 返回一个 HyperlinkCollection。Add() 接受目标单元格或范围以及地址,并返回新超链接的索引,该索引用于获取 Hyperlink 对象以进行进一步更改:
#include "aspose/cells_foss/Hyperlink.h"
sheet.GetCells()["A1"].PutValue("Documentation");
int linkIndex = sheet.GetHyperlinks().Add("A1", 1, 1, "https://example.com/docs");
Hyperlink link = sheet.GetHyperlinks()[linkIndex];
link.SetTextToDisplay("Documentation");
link.SetScreenTip("Open the docs site");
Workbook::GetDefinedNames() 以相同方式管理已命名范围——Add() 返回指向 DefinedNameCollection 的索引:
#include "aspose/cells_foss/DefinedName.h"
int nameIndex = workbook.GetDefinedNames().Add("Total", "=Data!$B$2:$B$3");
DefinedName total = workbook.GetDefinedNames()[nameIndex];
total.SetComment("Sum of tracked expenses");
Worksheet::GetValidations() 对数据验证规则遵循相同的集合模式,范围限定为 CellArea:
#include "aspose/cells_foss/Validation.h"
#include "aspose/cells_foss/CellArea.h"
int ruleIndex = sheet.GetValidations().Add(CellArea::CreateCellArea("B2", "B3"));
Validation amountRule = sheet.GetValidations()[ruleIndex];
amountRule.SetType(ValidationType::Decimal);
amountRule.SetOperator(OperatorType::GreaterThan);
amountRule.SetFormula1("0");
amountRule.SetErrorTitle("Invalid Amount");
amountRule.SetErrorMessage("Enter a positive number");
文档属性和工作簿设置
Workbook::GetDocumentProperties() 暴露核心和扩展的 OOXML 元数据字段(标题、作者、公司、经理等),Workbook::GetSettings() 控制工作簿级行为,例如日期系统:
#include "aspose/cells_foss/DocumentProperties.h"
workbook.GetDocumentProperties().SetCompany("Example Corp");
workbook.GetDocumentProperties().SetManager("Finance Team");
workbook.GetSettings().SetDate1904(false);
这些值在保存和重新加载时能够往返,如同单元格内容一样,这对于需要在生成的文件之间保持一致元数据的报告非常有用。
快速入门
Aspose.Cells FOSS for C++ 是使用 CMake 从源码构建的。克隆仓库后,可以将其作为子目录添加,或使用 FetchContent 拉取进来:
git clone https://github.com/aspose-cells-foss/Aspose.Cells-FOSS-for-Cpp.git
cmake_minimum_required(VERSION 3.15)
project(MyProject CXX)
set(CMAKE_CXX_STANDARD 17)
add_subdirectory(path/to/Aspose.Cells-FOSS-for-Cpp)
add_executable(MyApp main.cpp)
target_link_libraries(MyApp PRIVATE Aspose.Cells.Foss.Cpp)
一个最小化的电子表格管理示例 — 创建、样式化、保存并重新加载:
#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.SetName("Expenses");
Cells& cells = sheet.GetCells();
cells["A1"].PutValue("Category");
cells["B1"].PutValue("Amount");
cells["A2"].PutValue("Travel");
cells["B2"].PutValue(482.50);
cells["A3"].PutValue("Supplies");
cells["B3"].PutValue(129.99);
cells["B4"].SetFormula("=SUM(B2:B3)");
workbook.Save("expenses.xlsx");
Workbook loaded("expenses.xlsx");
Cells& loadedCells = loaded.GetWorksheets()["Expenses"].GetCells();
double total = loadedCells["B4"].GetValue().AsDouble();
return 0;
}
支持的格式
| 格式 | 扩展名 | 读取 | 写入 |
|---|---|---|---|
| Xlsx | .xlsx | ✓ | ✓ |
LoadFormat 和 SaveFormat 在此版本中均公开单个 Xlsx 值;Workbook(path) 与 Workbook(bytes) 构造函数加载 .xlsx 输入,而 Workbook::Save() 将 .xlsx 输出写入路径、流或内存缓冲区。
开源与许可
Aspose.Cells FOSS for C++ 在 MIT 许可证下发布。源码可在 GitHub 获取,且该库可在商业和开源项目中使用、修改和再分发,且无需运行时费用。