使用 C++ 将文本拆分为 Excel 文件中的列

Microsoft Excel 允许使用空格、逗号或其他字符等分隔符将文本拆分为多列。此功能在将数据库表导出的逗号分隔数据转换为表格形式等场景中很有帮助。为此,本文将教您如何使用 C++ 在 Excel 文件中将文本拆分为列。

用于在 Excel 文件中将文本拆分为列的 C++ API

我们将使用 Aspose.Cells for C++ API 将文本拆分为 Excel 文件中的列。它是一个本地 C++ 库,允许您创建、读取和修改 Excel 文件,而无需安装 Microsoft Excel。您可以通过 NuGet 安装 API,也可以直接从 下载 部分下载。

PM> Install-Package Aspose.Cells.Cpp

使用 C++ 将文本拆分为 Excel 文件中的列

以下是将文本拆分为 Excel 文件中的列的步骤。

以下示例代码演示了如何使用 C++ 将文本拆分为 Excel 文件中的列。

// 源目录路径。
StringPtr srcDir = new String("SourceDirectory\\");

// 输出目录路径。
StringPtr outDir = new String("OutputDirectory\\");

// 输出excel文件的路径
StringPtr outputFile = outDir->StringAppend(new String("TextToColumns.xlsx"));

// 创建 IWorkbook 类的实例
intrusive_ptr<IWorkbook> workbook = Factory::CreateIWorkbook();

// 访问第一个工作表
intrusive_ptr<IWorksheet> worksheet = workbook->GetIWorksheets()->GetObjectByIndex(0);

// 添加示例数据
intrusive_ptr<String> str = new String("John Teal");
worksheet->GetICells()->GetObjectByIndex(new String("A1"))->PutValue(str);
str = new String("Peter Graham");
worksheet->GetICells()->GetObjectByIndex(new String("A2"))->PutValue(str);
str = new String("Brady Cortez");
worksheet->GetICells()->GetObjectByIndex(new String("A3"))->PutValue(str);
str = new String("Mack Nick");
worksheet->GetICells()->GetObjectByIndex(new String("A4"))->PutValue(str);
str = new String("Hsu Lee");
worksheet->GetICells()->GetObjectByIndex(new String("A5"))->PutValue(str);

// 创建 ITxtLoadOptions 类的实例
intrusive_ptr<ITxtLoadOptions> options = Factory::CreateITxtLoadOptions();

// 指定分隔文本的分隔符
options->SetSeparator(' ');

// 将文本拆分为列
worksheet->GetICells()->TextToColumns(0, 0, 5, options);

// 保存输出的excel文件
workbook->Save(outputFile);
输出 Excel 文件的图像,显示分成两列的文本

输出 Excel 文件的图像,显示分成两列的文本

获得免费许可证

为了在没有评估限制的情况下试用 API,您可以申请 免费的临时许可证

结论

在本文中,您学习了如何使用 C++ 在 Excel 文件中将文本拆分为多列。您已经看到了完整的代码片段以及实现此目的所需的步骤。 Aspose.Cells for C++ 是一个强大的 API,它提供了许多附加功能来自动执行与 Excel 相关的任务。您可以通过访问 官方文档 来详细探索 API。如有任何问题,请随时通过我们的 免费支持论坛 与我们联系。

也可以看看